gpt4 book ai didi

c# - LINQ group by property 作为参数

转载 作者:行者123 更新时间:2023-11-30 20:05:53 25 4
gpt4 key购买 nike

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

// ....
}

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

最佳答案

如果你修改你的 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);

关于c# - LINQ group by property 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com