Search code examples
c#performancelinqdatabase-performance

Linq group by property performance


On a parametrizable query inspired by this post LINQ group by property as a parameter I've obtained a nice parametrizable query, but with one drawback on performances.

 public static void GetExpensesBy<TKey>( Func<Obj, TKey> myGroupingProperty)
    {
        var query = (from item in dataset
                     orderby item.ExpenseTime descending
                     select item).GroupBy(myGroupingProperty);
        // ....
    }
    // ..
    GetExpensesBy(p=> p.Column)

is much slower than the direct query

 var query = (from item in expense
                     orderby item.ExpenseTime descending
                     select item).GroupBy(p => p.Column);

The difference is about 2s vs 0.1s in a table of 13000 rows.

Would you have any idea how to improve the first syntax to improve the performance?


Solution

  • Change your parameter type for an Expression:

    public static void GetExpensesBy<TKey>( Expression<Func<Obj, TKey>> myGroupingProperty)
    {
     //...
    }
    

    Passing a Func<T> you are calling GroupBy from IEnumerable<T>