Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ group by property as a parameter

Tags:

c#

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.

like image 757
Jonas Schmid Avatar asked Oct 24 '25 16:10

Jonas Schmid


1 Answers

If you modify your GetExpenseBy as below

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);
like image 157
Ramesh Avatar answered Oct 26 '25 05:10

Ramesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!