3

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 any way to do this without running that LINQ query twice?
I cannot run it first into a temp variable because this query is itself part of a bigger LINQ query.

1
  • Yes. Try not to duplicate code. This causes more work and is prone to bugs. Commented May 9, 2012 at 19:42

5 Answers 5

7

I cannot run it first into a temp variable because this query is itself part of a bigger LINQ query.

You can use a let assignment within your query (or alternatively a projection that includes a helper field if you are using lambda syntax - that's what it gets compiled down to anyway):

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
            }
Sign up to request clarification or add additional context in comments.

1 Comment

That's fantastic. I never knew 'let' existed. Thanks.
2

Yes.

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

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

Now, when you're saying that the value can't be stuffed into a temp value, what do you mean? The above code certainly looks to be able to converted to that pattern.

Comments

1

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

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

Comments

0

You can still use a temporary variable, declare it but assign it inside that expression. Lots of code might make it hard to read in some situations, but at least reduces duplication.

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

Comments

0

Use LINQ's let statement

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.