4

I have a list of objects that I want to query using LINQ. I want to be able to group them by a property.

var query = from item in expense
    orderby item.ExpenseTime descending
    group item by item.Location;

var query = from item in expense
    orderby item.ExpenseTime descending
    group item by item.ExpenseType;

var query = from item in expense
    orderby item.ExpenseTime descending
    group item by item.Person;

Is there a way to specify the property as an argument of a method?

public static void GetExpensesBy(List<Expense> expense, Property myGroupingProperty)
{
    var query = from item in expense
                orderby item.ExpenseTime descending
                group item by item.myGroupingProperty;

    // ....
}

Note that after the query there is code that is generic and does not care about the group.

Jonas Schmid
  • 5,360
  • 6
  • 38
  • 60

3 Answers3

9

If you modify your GetExpenseBy as below

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

Then you can call this function as

GetExpensesBy(expense, item => item.Location);
GetExpensesBy(expense, item => item.Person);
GetExpensesBy(expense, item => item.ExpenseType);
Ramesh
  • 13,043
  • 3
  • 52
  • 88
0

Microsoft wrote a Dynamic Linq library.

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx

This lib will allow you to specify any of the Linq query dyanamically

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
0
public static void GetExpensesBy<T>(List<Expense> expense, Expression<Func<A,T>> groupbyExpression)
{
    var query = from item in expense
                orderby item.ExpenseTime descending;
    query.GroupBy(groupbyExpression);

    // ....
}

and create the expression like;

Expression<Func<Expense, string>> group = (q) => q.Location;
daryal
  • 14,643
  • 4
  • 38
  • 54