0

I'm trying to get my brain around LINQ Group By and I'm making headway, with one small flaw in my knowledge. I would like to group by multiple columns which I know I can do with new {} and some fields. Only issue is that I may or may not want to include them, based on some querystring values.

I've got this:

            var groupByResults = items.GroupBy(i => new 
            { 
                i.Product.Season.SeasonID,
                i.SourceLocation.LocationID, 
                i.Product.Brand.BrandID, 
                i.Product.Category.CategoryID, 
                i.Size.SizeID 
            });

I might want my anonymous object to only have the first field, or the last two, or whatever - depends which tickboxes have been ticked in the browser. I'm thinking ExpandoObject but I'm struggling how to get the relationship in there with regards to the 'i' from i => .....

As with everything I ask, it's just that I haven't figured out the right phrase for Google. Any help would be greatly appreciated.

Michael C
  • 231
  • 1
  • 7
  • You might want to try "*dynamic linq*".... it's old, but it works. – Stefan Nov 15 '18 at 13:48
  • From the way the question is, you most likely need a projection ( Select() ), which will allow you to have a selecton properties of the items. GroupBy() is making groups from items based on some property (it does not exclude members from the object). – Dimitar Nov 15 '18 at 13:50
  • Possible duplicate of [LINQ Grouping dynamically](https://stackoverflow.com/questions/17678197/linq-grouping-dynamically) – SᴇM Nov 15 '18 at 13:52
  • Using a [lambda based IEqualityComparer factory](https://stackoverflow.com/a/18984169/2557128), you can use the `GroupBy` that takes an `IEqualityComparer` and use a lambda that uses tests guarded by booleans. – NetMage Nov 15 '18 at 23:51

1 Answers1

0

You can initially include all possible group by entries and then "stub"(: true) some of them depending on your UI selection:

var groupByResults = items.GroupBy(i => new 
{ 
    SeasonID = UISeasonID != null ? i.Product.Season.SeasonID : true,
    LocationID = UILocationID != null ? i.SourceLocation.LocationID : true, 
    BrandID = UIBrandID != null ? i.Product.Brand.BrandID : true, 
    CategoryID = UICategoryID != null ? i.Product.Category.CategoryID : true, 
    SizeID = UISizeID != null ? i.Size.SizeID : true 
});
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26