LINQ集团物业作为参数 [英] LINQ group by property as a parameter

查看:154
本文介绍了LINQ集团物业作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想使用LINQ查询对象的列表。我希望能够通过一个属性组他们。

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.

推荐答案

如果您修改 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);
    // ....
}



然后就可以调用这个函数为

Then you can call this function as

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

这篇关于LINQ集团物业作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆