LINQ Distinct / Group By

LINQ offers up a nice way to group items and you can even reference the grouping values called keys.

Here’s an example of grouping a collection of Strings based on their length:

VB.NET

' VB requires the = Group part, but Group str By doesn't need the str part.
Dim myList = From str In fileStringCollection _
             Order By str.Length _
             Group By str.Length Into filGrouping = Group

C#

// Of course C# can't have the = Group part, requires the group str by to have the str part and requires the select
var myList = from str in fileStringCollection
             orderby str.Length
             group str by str.Length into filGrouping
             select new { filGrouping = filGrouping, Length = filGrouping.Key };

Here filGrouping behaves like a variable within the scope of the expression, we can look at the distinct values for the Length of the Strings by using the filGrouping.Key. Here we are returning the grouping, if you enumerate the grouping you get each of the Strings for that String Length.

For more on DISTINCT / GROUP BY see my more recent post (from a database point of view) SQL Server / Oracle: DISTINCT or GROUP BY

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s