Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count numbers in a List

Tags:

c#

algorithm

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?

like image 267
ddarellis Avatar asked Jan 23 '26 21:01

ddarellis


1 Answers

Very easy with LINQ :

var occurrenciesByNumber = list.GroupBy(x => x)
                               .ToDictionary(x => x.Key, x.Count());

Of course, being your numbers represented as strings, this code does distinguish for instance between "001" and "1" even if conceptually are the same number.

To count numbers that have the same value, you could do for example:

var occurrenciesByNumber = list.GroupBy(x => int.Parse(x))
                               .ToDictionary(x => x.Key, x.Count());
like image 129
digEmAll Avatar answered Jan 26 '26 10:01

digEmAll