codecompleting
codecompleting

Reputation: 9621

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 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?

Upvotes: 2

Views: 6169

Answers (3)

Jon Benedicto
Jon Benedicto

Reputation: 10582

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
}

Upvotes: 8

Nour
Nour

Reputation: 5449

var list = from product in productList group product by product.Type;

Upvotes: 0

Reddog
Reddog

Reputation: 15579

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

Upvotes: 3

Related Questions