4

我有一个要使用 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;

    // ....
}

请注意,查询后有通用代码,不关心组。

4

3 回答 3

9

如果您修改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);
于 2012-05-04T09:03:18.020 回答
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;
于 2012-05-04T09:02:33.980 回答
0

Microsoft 编写了一个 Dynamic Linq 库。

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

此库将允许您动态指定任何 Linq 查询

于 2012-05-04T08:58:41.050 回答