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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With