What is the purpose of the 'Let' statement in a LINQ query?

Asked

Viewed 960 times

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 estate Data is the type Nullable<DateTimeOffset> and so Resharper shows me a warning saying:

Possible System.Invalidoperationexception

And give me a hint to change that 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 to me that the let creates a variable in the middle of the query, that’s right?

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 are set a variable for the declaration dateTimeOffset, which is used further down:

    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 being very useful. It is more useful when the field is calculated, or derived from other fields. You might as well do so:

    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 to me that Let creates a variable in the middle of the query, is that right? If so, why didn’t Resharper indicate to do where em.Data != null?

Because he doesn’t interpret attribution as redundant, especially because you use it select new to return a return object.

2

This is exactly what it is. When you will sometimes use an intermediate result, it may be interesting to use a variable to keep a "cache" of the data, which is the normal function of every variable. You can even avoid some side effect of performing several times some type 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 her scope is consultation.

Documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.