How do I do "let" in dynamic LINQ?

How to write this query in dynamic linq? I know how to make a choice, but how do I make a "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
                             };

      

+3


source to share


1 answer


There is no equivalent let

in linq expression method syntax, nor in dynamic LINQ .

let

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

In your case, just add variable initialization let

to select

.

Like this in the 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 similarly with dynamic LINQ (select clause like 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.

This would be similar to other expression methods. The only thing you need is to use the value directly instead of the alias let

.

+4


source







All Articles