What is the 'let' statement in a LINQ query?

4

I have the following LINQ query:

var source = from em in query
             select new
             {
                 Id = em.UniqueID,
                 Data = em.Data == DateTime.MinValue ? "" : em.Data.Value.ToString("dd/MM/yy HH:mm")                     
             };

The Data property is of type Nullable<DateTimeOffset> and so the Resharper shows me a warning saying:

  

Possible System.InvalidOperationException

And give me the 'hint' of changing this query to

var source =  from em in query
              let dateTimeOffset = em.Data
              where dateTimeOffset != null
              select new
              {
                  Id = em.UniqueID,
                  Data = dateTimeOffset == DateTime.MinValue ? "" : dateTimeOffset.Value.ToString("dd/MM/yy HH:mm")
              };

It seems that let creates a variable in the middle of the query, is it?

    
asked by anonymous 14.12.2015 / 17:15

2 answers

5

let is used to define variables at expression time.

In this case:

var source =  from em in query
              let dateTimeOffset = em.Data

You set a variable for the dateTimeOffset statement, which is used below:

    where dateTimeOffset != null
    select new
    {
        Id = em.UniqueID,
        Data = dateTimeOffset == DateTime.MinValue ? "" : dateTimeOffset.Value.ToString("dd/MM/yy HH:mm")
    };

But in this case it is not very useful. It is most useful when the field is calculated, or derived from other fields. You might as well do it:

    where em.Data != null
    select new
    {
        Id = em.UniqueID,
        Data = em.Data == DateTime.MinValue ? "" : em.Data.Value.ToString("dd/MM/yy HH:mm")
    };
  

It seems that let creates a variable in the middle of the query, is that right? If this is because Resharper did not indicate to where em.Data != null ?

Because it does not interpret the assignment as redundant, especially since you use select new to return a return object.

    
14.12.2015 / 17:19
2

That's exactly it. When you are going to use an intermediate result sometimes, it may be interesting to use a variable to hold a data cache, which is the normal function of every variable. You can even avoid some side effect of running several times some kind of expression that can produce different results.

Of course this example is not the best because the gain is small, but it is still useful.

Obviously the scope of it is the query.

Documentation .

    
14.12.2015 / 17:20