How to C# Linq Group By by paramater/field names
In C# LINQ, GroupBy is used to group elements in a collection based on a key and then perform operations on each group. It is similar to SQL GROUP BY.
Key concepts of LINQ GroupBy
Key (g.Key) → grouping value
Group → collection of items in each group
Returns IGrouping<TKey, TElement>
When to use GroupBy?
Use it when you need:
Data categorization (e.g., by department, city, type)
Aggregations (sum, count, average)
Reporting and analytics
Transforming flat data into grouped structure
Advantages of GroupBy
Very expressive and readable
Works well with aggregation functions
Avoids manual looping logic
Similar to SQL GROUP BY
Common mistakes
Forgetting to use .Select() after grouping when transforming output
Thinking GroupBy returns a list (it returns grouped collections)
Using it when sorting or filtering would be enough
LINQ GroupBy Examples
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 (Method Syntax)
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 (Query Syntax)
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.
Iterating over groups
foreach (var group in results)
{
Console.WriteLine(group.Key); // group name
foreach (var student in group)
{
Console.WriteLine(" " + student.Name);
}
}