user8253642
user8253642

Reputation:

Access values from LINQ GroupBy

I have a linq query looking like this:

            var myGrouping = (
                from p in context.Products
                join pt in context.ProductTypes on p.productId equals pt.productId
                select new
                {
                    ProductName = p.productName,
                    Type = pt.productType
                }).GroupBy(x => x.ProductName ).ToList();

This gives me what I'm looking for, a group for each ProductName with the Types displayed with them. Now, what I'm looking to do is check each group and see if the ProductType ever differs INSIDE these groupings, which is an error I sometimes get in the database.

I've tried a few things to access this data, and it seems like I can use item.Distinct().Skip(1).Any() to check through these groupings and see if they differ. Problem is only that I don't know how to access the ProductName and Type, to loop over it. I've tried things like

foreach (IGrouping<string, string?> ProductGroup in myGrouping)

and things along those lines but it never seems accessable. My question is, how do I access elements in IGroupings like this?

Upvotes: 12

Views: 11915

Answers (2)

Looki
Looki

Reputation: 952

When using GroupBy you can access:

  • the Key by which was sorted with list.Key
  • the List for each group with list.ToList()

So:

foreach(var group in input.GroupBy(it => it.Sort)) 
{
    var sort = group.Key;
    var list = group.ToList();
}

Upvotes: 21

Koderzzzz
Koderzzzz

Reputation: 869

Use it like this

 var myGrouping = (
            from p in context.Products
            join pt in context.ProductTypes on p.productId equals pt.productId
            select new
            {
                ProductName = p.productName,
                Type = pt.productType
            }).GroupBy(x => new{x.ProductName,x.Type } ).Select(x=>new {ProductName =x.Key.ProductName ,Type=x.Key.Type}).ToList();

Upvotes: 0

Related Questions