How to group by a given column in a List of T collection using linq?
Say I have a collection of
IList<Products> products
And开发者_StackOverflow中文版 I want to group by Product.Type in that collection, where Type is a Guid.
Just thinking about it, I really just need to Order by the Product.Type, wouldn't ordering and grouping return the same results?
Ordering and grouping are not the same thing, no. Grouping is generally implemented using ordering, but grouping implies the isolation of the items in the group from items in another group, whereas ordering merely arranges the items so that the items of one group are collected together in a particular section of the collection.
For example:
// Grouping
var groups = products.GroupBy(x => x.Type);
foreach (var group in groups)
{
Console.WriteLine("Group " + group.Key);
foreach (var product in group)
{
// This will only enumerate over items that are in the group.
}
}
// Ordering
var ordered = products.OrderBy(x => x.Type);
foreach (var product in ordered)
{
// This will enumerate all the items, regardless of the group,
// but the items will be arranged so that the items with the same
// group are collected together
}
There is an OrderBy extension method you could use.
var orderedProducts = products.OrderBy(p => p.Type);
Or for grouping, use GroupBy:
var groupedProducts = products.GroupBy(p => p.Type);
var list = from product in productList group product by product.Type;
精彩评论