ineffable p ineffable p - 1 year ago 100
C# Question

LINQ Grouping dynamically

I have a class list of records, so user can select to group rows dynamically by property name. For example

MenuText
,
RoleName
or
ActionName
. Then I have to execute grouping so I need a generic method to handle grouping by passing column name.

Example :

public class Menu
{
public string MenuText {get;set;}
public string RoleName {get;set;}
public string ActionName {get;set;}
}

public class Menus
{
var list = new List<Menu>();
list.Add( new Menu {MenuText="abc",RoleName ="Admin", ActionName="xyz"};
list.Add( new Menu {MenuText="abc",RoleName ="Admin", ActionName="xyz"};
list.Add( new Menu {MenuText="abc1",RoleName ="Admin1", ActionName="xyz1"};
list.Add( new Menu {MenuText="abc1",RoleName ="Admin1", ActionName="xyz1"};

/// columnName :- Name of the Menu class ( MenuText or RoleName or ActionName)

public IEnumerable<IGrouping<string,IEnumerable<Menu>>> GroupMenu(string columnName)
{
// Here I want to get group the list of menu by the columnName
}
}

Answer Source

If you're not working with a database you can use Reflection:

private static object GetPropertyValue(object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

Used as:

var grouped = enumeration.GroupBy(x => GetPropertyValue(x, columnName));

This is a pretty raw solution, a better way should be to use Dynamic LINQ:

var grouped = enumeration.GroupBy(columnName, selector);

EDIT Dynamic LINQ maybe needs some explanations. It's not a technology, a library or a brand new framework. It's just a convenient name for a couple (2000 LOC) of helpers methods that let you write such queries. Just download their source (if you don't have VS samples installed) and use them in your code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download