What is that IGrouping result returned from group by LINQ queries?
Copyright © 2007-2012 www.AspDotNetFaq.com
I dont know how much you people use LINQ but for me it was like a blessing.
Since I figured out how helpful it is I never really looked back.
But this post is not about obvious usefulness of LINQ, everyone should know that by now!!!
I would like to clarify some exotic details on the results we get from group by queries with LINQ and explain a little bit more on that infamous
IGrouping collection.
So let us set up a simple example. We will (over)use a corny Product class with only two properties:
public class Product
{
public string Name { get; set; }
public int YearOfProduction { get; set; }
}
Then we can create an array of some imaginary products so we could group them:
var products = new[]
{
new Product {Name = "Flashlight", YearOfProduction = 2009},
new Product {Name = "Nanobot", YearOfProduction = 2012},
new Product {Name = "Disintegrator", YearOfProduction = 2012}
};
And here is the actual LINQ query that returns us the products grouped by year of their production:
var grouped = from product in products group product by product.YearOfProduction;
This all works as expected. Its simple group by query and i wont go deeper into the subject you can find more examples on the
101 LINQ Samples page.
Let us focus on the result of that query.
What LINQ returned to us in variable
grouped is a unusual collection of objects that have a common key.
Its actually object of
IEnumerable<IGrouping<TKey, TElement>> where in our case
TKey is of type
integer and
TElement is of type
Product.
Then when we iterate with foreach trough that collection each time we get a object of type
IGrouping<TKey, TElement> and in this specific example that is
IGrouping<int, Product>.
So lets dig dipper and examine it:
First of all this element has a
Key property that holds the value by which the group is grouped (in our case its integer with the year of production).
Next, that element implements
IEnumerable<TElement> so we can iterate trough it (again with foreach) and get all the elements in that group (in this case those are the products produced in that year).
And last but not the least, we can use
Count() to find out how many items we have for that year.
Yes, I know it sounds little confusing but i'm sure a little bit of code will clarify everything:
foreach (var group in grouped)
{
Console.WriteLine("Total of {0} products produced in year {1}:", group.Count(), group.Key);
foreach (var item in group)
{
Console.WriteLine(item.Name);
}
Console.WriteLine();
}
And the magic console output looks like this:
So now that we know how LINQ and IGrouping works we can easily iterate trough each group and at once get all the data we need.
Now isn't that nice? Don't you just love programming in .NET?
Here is the link to the
Visual Studio 2008 solution with the code from this post.
Copyright © 2007-2012 www.AspDotNetFaq.com