Showing that fear of mediocrity can make the world a better place.

Posts tagged “count

LINQ in a blink:Group by with count

LinqInABlink

Ever come across a situation where you wanted to find how many of a similar object you had in a list?

Sample code: All of the code used for this example is located on GitHub here https://github.com/objectatrest/BlogCode/tree/master/LINQ_in_a_blink/LinqInABlink

In SQL it would look something like this:

GroupAndCountSQLData

GroupAddCountSQL

And you would get the result

GroupAndCountResults

Well it’s pretty easy to query a collection of objects using LINQ in a similar way:

GroupAndCountData

GroupAddCount

Which could print out to the console as

GroupAndCountResultsLINQ

We can extend it to only include those that have more than one occurrence of the grouping.

SQL:

GroupAddCountFilteredSQL

GroupAndCountFilterResults

LINQ:

GroupAddCountFiltered

GroupAndCountFilterResultsLINQ

https://github.com/objectatrest/BlogCode/tree/master/LINQ_in_a_blink/LinqInABlink