How to C# Linq Group By by paramater/field names
Consider that we have given a list of Employee's. Assume that Employee class have several parameters such as
• ID,
• Name,
• Surname,
• Address,
• CompanyID,
• etc.
The simplest group by statement can be written in C# Linq as given below.
Non-Query Linq Group By Example
var results = list.
GroupBy(e => e.CompanyID).
ToDictionary(e => e.Key, e => e.ToList());
where the results is a dictionary of CompanyID to the Employee's working at the same company. Query version can be written as given below.
Query Linq Group By Example
var results = from e in list
group by e.CompanyID into g
select new { CompanyID = g.Key, Employees = g.ToList() };
Now, we will give a "group by example" frequently used for client-service applications. Assume that, you have given the "group by" dimension as a String (e.g. var groupName = "CompanyID";
).
Applying Linq Group by statement using Parameter/Field Name
var results = list.GroupBy(e => e.GetType().GetProperty(groupName).
GetValue(e, null).ToString()).
ToDictionary(e => e.Key, e => e.ToList());
If you need multiple group by dimensions, considering that we have given list of groupNames, check the solution given below.
Multiple Group By statements for given parameter/field names
var results = list.GroupBy(e =>
new Tuple<String, String>(
e.GetType().GetProperty(groupNames[0]).
GetValue(e, null).ToString(),
e.GetType().GetProperty(groupNames[1]).
GetValue(e, null).ToString())).
ToDictionary(e => e.Key, e => e.ToList());
You might apply more dimensions using a larger Tuple.