In C# i have a List which contains numbers in string format. Which is the best way to count all this numbers? For example to say i have three time the number ten..
I mean in unix awk you can say something like
tempArray["5"] +=1
it is similar to a KeyValuePair but it is readonly.
Any fast and smart way?
(As noted in digEmAll’s answer, I’m assuming you don’t really care that they’re numbers – everything here assumes that you wanted to treat them as strings.)
The simplest way to do this is to use LINQ:
You could build the dictionary yourself, like this:
… but I prefer the conciseness of the LINQ approach 🙂 It will be a bit less efficient, mind you – if that’s a problem, I’d personally probably create a generic “counting” extension method:
(You might want another overload accepting an
IEqualityComparer<T>.) Having written this once, you can reuse it any time you need to get the counts for items: