Home > database >  EF Core choose object with conditions
EF Core choose object with conditions

Time:04-23

Can't get into one thing. I would be very grateful for help.

And so, to the problem: I have a list of Foos objects with inputs a and b that must meet two conditions, for example

db.Foos.Where(foo => foo.a == a && foo.b == b).ToList()

I need to calculate Delta(foo) on the Foos list, and select the object from the list where this delta is minimal.

Delta example:

foo => (a*2   b) - (foo.a   foo.b)

Actually a question how can I select this object?

CodePudding user response:

To get the foo instance with the smallest delta value you can sort the filtered result set by the delta value so it is ordered with the smallest value first in the list and then take the first item from that result set.

var fooWithSmallestDelta = db.Foos
    .Where(foo => foo.a == a && foo.b == b)
    .OrderBy(foo => (a*2   b) - (foo.a   foo.b))
    .FirstOrDefault();
  • Related