I have a List object which contains Id values for example it contains: 1,2,10,1,23,11,1,4,2,2,.. etc I need to find out how many times "1","2",... etc have occured using Linq in C#
kindly help.
That's pretty simple using Enumerable.GroupBy
:
var grouped = list.GroupBy(x => x);
foreach (var group in grouped)
{
Console.WriteLine("{0} appears {1} times", group.Key, group.Count());
}
Or alternatively:
var query = list.GroupBy(x => x, (x, g) => new { Key = x, Count = g.Count() }));
foreach (var result in query)
{
Console.WriteLine("{0} appears {1} times", result.Key, result.Count);
}
(The difference is just in when we transform the group into a result, really.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With