Linq GroupByMany dynamically

Shawn asked me in my last post about GroupByMany how to use it dynamically.

The answer is not easy. So here is a new post to answer to this interesting question.

First you must learn a few things about being dynamic with linq.
There is a very good sample from the C# team (actually we can consider it as a library provided as a sample). ScottGu has post about it here:

One of the power of linq is to be checked at compile-time. You must be aware that using this kind of solution may raise some exceptions at runtime.

Now I have added the Dynamic.cs file to my project and I can use a very useful method: DynamicExpression.ParseLambda.

Here is a new GroupByMany extension method which accepts a list of strings instead of delegates to define all the groupings.
The goal is to call the first GroupByMany method. To do this we have to go from a single string defining the name of a property in the TElement class to a Func<TElement, object>.
We could do this building the expression manually but DynamicExpression.ParseLambda will do it in just a single line.

public static class MyEnumerableExtensions
public static IEnumerable<GroupResult> GroupByMany<TElement>(
this IEnumerable<TElement> elements, params string[] groupSelectors)
var selectors
new List<Func<TElement, object>>(groupSelectors.Length);
foreach (var selector in groupSelectors)
LambdaExpression l
typeof(TElement), typeof(object), selector);
<TElement, object>) l.Compile());
return elements.GroupByMany(selectors.ToArray());
Now we can write directly:
DataContext = customers.GroupByMany(Country, City);

instead of :
DataContext = customers.GroupByMany(c => c.Country, c => c.City);

The full project is attached to this post. (VS2008.)

Comments (9)

  1. Sharepoint Two New Tools for SharePoint Development [Via: axshon ] WPF Visio 2007 to XAML Export Add-in…

  2. Link Listing – February 6, 2008

  3. Shawn says:

    Wow Mitsu, Thank you so much for your post. I’ve found both to be very enlightening and informative. As I learn more about LINQ and Lambda expressions,  articles like these really showcase the power behind these new features and what is now possible. Thanks again.


  4. Craig says:

    This looks great Mitsu. It may also be possible to create a type-safe dynamic GroupByMany method using a similar technique to that referenced on ScottGu’s post about dyanamic linq I havent tried to implement this approach myself yet, but it seems like it could be useful in avoiding the exceptions that may be raised at runtime by the above technique. Do you think this approach is worth persuing? I may try to implement this if I get some time in the near future!

  5. Mitsu Furuta says:

    Hi Craig,

    My first sample was type-safe:

    I was explicitly showing here how to do it dynamically.

    The PredicateBuilder is solving something else. It allows you to dynamically compose existing predicates with logical ‘or’ or ‘and’.

    It does not help you to build ‘p => p.Description’ dynamically.

  6. Here are some good resources from Mitsu Furuta to get you started:

  7. Phiphy says:

    Could you help me with this:

    if I use the Dynamics libr. I am not able to cast the grouped element back to my original type – List<MyClass>.  

    If I use a ‘regular’ group by (lista.GroupBy(x => new { x.Godina, x.Broizv }) ) I’m able to cast to List<MyClass>.

    Could you help me out with this?

    var listaGroupByIzvod = lista.GroupByMany("Godina", "Broizv");

    var listaGroupByIzvod = lista.GroupBy(x => new { x.Godina, x.Broizv });

    foreach (var listaGroup in listaGroupByIzvod)


    List<MyClass> tempListaIzvodi = listaGroup.ToList<MyClass>();


  8. Devi Raghavan says:

    Thanks for your help with GroupByMany. I would like to know how I could dynamically order by each group and its contents. I have a component one grid which could be grouped by multiple columns and each group  could be ordered ascending or descending. That is the next thing that I am working on. Any help would be greatly appreciated. Thanks.

  9. nlips says:

    When you use GroupBy to do some aggregations (= analysis query), you can now use the .QueryByCube() function provided by AdaptiveLINQ (

    Cube dimensions and measures are defined by C# lambda expressions.

    GroupBy key selector are determined at runtime by properties used in the query.

    For example "Sales per customer" can be written:


    .Select(x => new {

     Customer = x.CustomerName,

     Sales = x.Sales


    "Sales per customer and product cactegory" can be written:


    .Select(x => new {

     Customer = x.CustomerName,

     Category = x.ProductCategory

     Sales = x.Sales


    And you can specify your query using other LINQ operator like OrderBy, Where,…

    "Sales in France per customer and product cactegory":


    .Where(x => x.Territory == "FR")

    .Select(x => new {

     Customer = x.CustomerName,

     Category = x.ProductCategory

     Sales = x.Sales