我有一个要使用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;
// ....
}
请注意,在查询之后,代码是通用的,并不关心组。
答案 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)
Microsoft编写了一个Dynamic Linq库。
http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx
此lib将允许您指定任何Linq查询dyanamically
答案 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;