How to C# Linq Group By by paramater/field names

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.


added 6 years 11 months ago

- How to POST and GET url with parameters in C#?
- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?
2
1