I'm using streamreader now to read a file of people names, it is a text file, of people first names, so there are obviously duplicates, and i want to be able to display how many people have the same now so for example:
josh
alex
josh
john
alex
I want it to say,
josh 2
alex 2
john 1
but I can't seem to find an easy way of doing this, what would be the easiest way about doing this,
You could of course also do something like this (error checking omitted), using Linq:
Depending on the size of the file, this might be desirable to get rid of the stream; however, this isn't to say that if the file was considerably large for memory that you should use
ReadLine
.Try this with LINQ.
First read your text file to a
List<string>
using this code:You need to define a class where you will have name and accordingly the count:
And finally use this
Lambda
expression to get desiredList<string>
Now iterate through the list to get the names and the count of duplicates.
try this offline solution
Store all names in a
Dictionary<string, int> names
.Use something like this for each row:
(it should set the count to one if the item do not exist)
I'd say use a
Dictionary<string, int>
.Of course there are many different paths to a solution, but this is how I would tackle it. I haven't run this code yet, but this will help you I think.