Conditional operator without evaluation twice?

Say I have the following:

MyDate = 
  (db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue == DateTime.MinValue) 
    ? DateTime.Now 
    : db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue

Is there a way to do this without running this LINQ query twice?
I cannot start it first in the temp variable, because this query itself is part of a larger LINQ query.

+3
source share
5 answers

I cannot start it first in the temp variable because this request is itself part of a larger LINQ request.

You can use assignment letin your query (or, alternatively, a projection that includes an auxiliary field, if you use lambda syntax - that it has been compiled so far):

var query = from foo in db.Bar
            let bar = db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue
            select  new 
            {
               MyDate = bar == DateTime.MinValue ? DateTime.Now : bar
            }
+7
source

Yes.

var dateValue = db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue;

return dateValue == DateTime.MinValue ? DateTime.Now : dateValue;

, , temp, ? , , , .

+2

Evaluate once and assign a variable - use the variable in the conditional expression:

var item = db.MyTables.FirstOrDefault(x => x.MyID == idToFind);

MyDate = (item.DateValue == DateTime.MinValue) 
    ? DateTime.Now 
    : item.DateValue

Or:

var theDate = db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue;

MyDate = (theDate == DateTime.MinValue) 
    ? DateTime.Now 
    : theDate
+1
source

You can still use a temporary variable, declare it, but assign it inside this expression. Plenty of code can make reading difficult in some situations, but at least reduces duplication.

MyDate = 
  (temp = db.MyTables.FirstOrDefault(x => x.MyID == idToFind).DateValue) == DateTime.MinValue) 
    ? DateTime.Now 
    : temp
0
source

Use the LINQ statement let

from a in someSource
let d = db.MyTables.FirstOrDefault(x => x.MyID == a.idToFind).DateValue
select (d == DateTime.MinValue) ? DateTime.Now : d;
0
source

All Articles