LINQ group by property作为参数

时间:2012-05-04 08:46:44

标签: c# linq

我有一个要使用LINQ查询的对象列表。我希望能够通过财产对它们进行分组。

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;

有没有办法将属性指定为方法的参数?

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

    // ....
}

请注意,在查询之后,代码是通用的,并不关心组。

3 个答案:

答案 0 :(得分:6)

如果您修改GetExpenseBy如下

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);
    // ....
}

然后您可以将此功能称为

GetExpensesBy(expense, item => item.Location);
GetExpensesBy(expense, item => item.Person);
GetExpensesBy(expense, item => item.ExpenseType);

答案 1 :(得分:0)

答案 2 :(得分: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);

    // ....
}

并创建像;

这样的表达式
Expression<Func<Expense, string>> group = (q) => q.Location;