I have a simple method containing a query to calculate some values.
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings)
{
return myThings.Where(x => x.Id == 1)
.Select(x => (x.ThisValue * x.That))
.Sum();
}
My aim is to modify the method to allow me to specify the x.ThisValue field being queried in the object.
If I were to specify the Where clause of my query, I might pass a predicate but in this case, I only want to alter the value of x.ThisValue.
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings, Func<ThingsViewModel,bool> predicates)
{
return myThings.Where(predicates)
.Select(x => (x.ThisValue * x.That))
.Sum();
}
Ideally, I'd like to pass in something like:
MyQueryBuilderMethod(things, x.ThisOtherValue)
Following should work:
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings,
Func<ThingsViewModel, decimal> thisValue)
{
return myThings.Where(x => x.Id == 1)
.Sum(x => (thisValue(x) * x.That));
}
I also replaced the Select(...).Sum()
by the shorter but equivalent Sum(...)
.
You then can call it like the following:
var result = MyQueryBuilderMethod(myThings, t => t.ThisValue);
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