0

I would like to know how to group data avoiding anonymous types, because the keys may be one, two.. according to customer selection.

Example:

We have a class

public class Customer
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string Location { get; set; }

    public char Genre { get; set; }
}

And through a checked list box, you may select parameters to group data, where the options would be:

  • Name
  • Age
  • Location
  • Genre

So we may have between 1 and 4 keys to group data.

I want to avoid a switch case or multiple if statements to get the correct IGrouping data.

I want to avoid:

 public IGrouping<object,Customer> GetGroups(IEnumerable<Customer> data)
 {
    if("Name is selected")
    {
        return data.GroupBy(e => e.Name);
    }
    if("Name and Age are selected")
    {
        return data.GroupBy(e => new { e.Name, e.Age });
    }
}
Jesus Hedo
  • 119
  • 1
  • 1
  • 10
  • 1
    Can you add some code? – Avinash Reddy Jul 16 '21 at 13:09
  • I let you an example of what I want to avoid, because what I need, I don't know how to implement it. Thoughts? – Jesus Hedo Jul 16 '21 at 13:18
  • You probably need to take a look at IQueryable, https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.groupby?view=net-5.0 – madoxdev Jul 16 '21 at 13:20
  • I mean... you could perhaps use return `Tuple.Create(e.Name, e.Age)`, but... if anything that *loses* information compared to anonymous types, as now all you know is that it returns a `string` and `int` (or whatever) - not *what* that `string` is... what is the thing you're trying to avoid here? – Marc Gravell Jul 16 '21 at 13:31

2 Answers2

2

Not sure if this is something you are looking for, but might be helpful:

return data.GroupBy(g =>
  new {
    Name = includeName ? g.Name : null,
    Age = includeAge ? g.Age : null,
    ... 
  });
Grigoryants Artem
  • 1,401
  • 2
  • 15
  • 32
1

This one works, it's a bit cheating, you just make sure the grouping key have proper values as per what you want your grouping to become. Below works, because if you don't want to group by a given property, you just set a default (same for every item) value.

    bool groupByName = false;
    bool groupByAge = false;
    bool groupByLocation = false;
    bool groupByGenre = true;
    
    var result = from x in items
                 group x by new { 
                                    Name = (!groupByName ? "" : x.Name), 
                                    Age = (!groupByAge ? 0 : x.Age),
                                    Location = (!groupByLocation ? "" : x.Location),
                                    Genre = (!groupByGenre ? ' ' : x.Genre)
                                } 
                                    into g
                 select g;
madoxdev
  • 3,770
  • 1
  • 24
  • 39