Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core 8 - more efficient way to code this? Something like a SQL Case statement?

The code:

var primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Prime").FirstOrDefault();
if (primeCtr == null)
   primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Original Prime").FirstOrDefault();

Explanation: If a contractor of type "Prime" exists, use that one, else use the "Original Prime"

I could have coded this using ? : expression but I think it would have been less efficient?

var primeCtr = con.Contractors?.Where(ctr => ctr.Type == "Prime").Any() ? con.Contractors?.Where(ctr => ctr.Type == "Prime").FirstOrDefault() : con.Contractors?.Where(ctr => ctr.Type == "Original Prime").FirstOrDefault();

The query for "Prime" would get executed twice I think?

Just trying to determine if there is a more elegant way to express this using EF Core 8? This is my first EF Core app and I haven't used the old EF in several years, so could be rusty.

like image 583
jrichview Avatar asked Aug 05 '26 18:08

jrichview


1 Answers

The most common way to do this is ordering by a predicate that expresses preference and take the first:

con.Contractors.OrderByDescending(ctr => ctr.Type == "Prime").FirstOrDefault()

If there are more types you'll have to filter out "Prime" and "Original Prime" (add a Where before the ordering).

The ordering is descending because then the one where ctr.Type == "Prime" is true floats to the top.

like image 67
Gert Arnold Avatar answered Aug 09 '26 05:08

Gert Arnold