How to do "let" in dynamic LINQ?

c# dynamic-linq linq linq-to-entities

Question

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
                             };
1
3
2/10/2013 4:30:04 PM

Accepted Answer

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.

4
2/11/2013 8:57:44 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow