How can we build the groupBy expressions based on multiple properties which can change in number? I got a list of objects of class C. All the groupby examples I can find are based on pre-determined properties. How can we build groupBy expression on the fly based on number of properties passed in by the user?
Please note that I don't know exact properties as it is different for every real project. So the code cannot assume that GroupByAttribute1, GroupByAttribute2 etc will exist. Need a solution which takes all grouping input parameters and build groupby as per values of them.
class C
{
public int Id { get; set; }
public string GroupByAttribute1 { get; set; }
public string GroupByAttribute2 { get; set; }
public string GroupByAttribute3 { get; set; }
}
private static void TestGroupBy()
{
//grouping attribute change on the fly
GroupBy(new List<string> { "GroupByAttribute1", "GroupByAttribute3" });
GroupBy(new List<string> { "GroupByAttribute2" });
}
private static void GroupBy(List<string> groupByAttributes)
{
List<C> items = new List<C>
{
new C { Id = 0, GroupByAttribute1 = "A", GroupByAttribute2 = "C", GroupByAttribute3 = "B" },
new C { Id = 1, GroupByAttribute1 = "A", GroupByAttribute2 = "D", GroupByAttribute3 = "B" },
new C { Id = 2, GroupByAttribute1 = "X", GroupByAttribute2 = "N", GroupByAttribute3 = "Z" },
new C { Id = 3, GroupByAttribute1 = "X", GroupByAttribute2 = "N", GroupByAttribute3 = "Z" }
};
/* Grouping based on fixed properties can be done like below
var f = items.GroupBy(i => new
{
Attribute1 = i.GroupByAttribute1,
Attribute2 = i.GroupByAttribute3
});*/
//How to build groupBy expression based on grouping attributes that can change with the call?
var f2 = items.GroupBy(i => new
{
foreach (var propertyToGroupBy in groupByAttributes)
{
}
});
}