LINQ Grouping dynamically

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.

Leave a Comment