Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I use Func<> to modify a single condition of a lambda

Tags:

c#

linq

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)
like image 408
Nick Avatar asked Sep 30 '22 23:09

Nick


1 Answers

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);
like image 130
Christoph Fink Avatar answered Oct 13 '22 12:10

Christoph Fink