Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<int> filtering using linq

Tags:

c#

.net

linq

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.

like image 878
skamale Avatar asked Nov 28 '22 09:11

skamale


1 Answers

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.)

like image 97
Jon Skeet Avatar answered Dec 16 '22 01:12

Jon Skeet