Jonathan
Jonathan

Reputation: 1755

How to do "let" in dynamic LINQ?

How would I write this query in dynamic linq? I know how to do the select, but how do I do the "let"?

var qry = from sr in data.Addresses
                  let AddressType_Desc = sr.AddressType.AddressType_Desc
                  let Country_Desc = sr.Country.Country_Desc
                  where sr.Customer_GUID == CustomerGuid
                  select new
                             {
                                 sr.Address_GUID,
                                 sr.People_GUID,
                                 sr.AddressType_GUID,
                                 AddressType_Desc,
                                 sr.Address1,
                                 sr.Address2,
                                 sr.City,
                                 sr.State,
                                 sr.Zip,
                                 sr.County,
                                 sr.Country_GUID,
                                 Country_Desc,
                                 sr.UseAsMailing
                             };

Upvotes: 3

Views: 1032

Answers (1)

mipe34
mipe34

Reputation: 5666

There is no equivalent of let in linq expression method syntax, as well in dynamic LINQ.

Let can only help you to make your queries more readable. It simply works as an alias or local variable. You can imagine, that in method syntax you won't be able to access it outside the scope of the method declared it.

In your case, just simply put the let variable initiation into the select.

Like this in linq method syntax:

var qry = data.Adresses.Where(sr => sr.Customer_GUID == CustomerGuid)
                       .Select(sr => new {
                                            sr.Address_GUID,
                                            ....

                                            sr.AddressType.AddressType_Desc, 
                                            sr.Country.Country_Desc
                                         });

Or similar with dynamic LINQ (select clause as string):

var qry = data.Adresses.Where(sr => sr.Customer_GUID == CustomerGuid)
                       .Select("new (Address_GUID, AddressType.AddressType_Desc, Country.Country_Desc)");

And you will get the same result as with linq query syntax.

It would be similar for other expression methods. Only thing you need, is to use the value directly instead of the let alias.

Upvotes: 4

Related Questions