Is it wrong to call First () several times in LINQ Select?

I have a LINQ statement where I would like to combine in the first address with the alias "Me".

using (var ctx = new DataEntities())
{
  return from c in ctx.Customers.Include("Addresses")
         let m = from a in c.Addresses where a.Nickname == "Me" select a
         where m.Any()
         select new
         {
           Id = c.CustomerId,
           m.First().Name,
           m.First().Address1,
           m.First().Address2,
           m.First().City,
           m.First().State,
           m.First().Zip,
           m.First().Email,
           m.First().PhoneNumber
         };
}

I am wondering:

  • Will performance deteriorate if I call first several times, like this?
  • Is there a better LINQ statement for this?
  • Just realized if I need .Include ("Addresses")?
+3
source share
1 answer

For LINQ to SQL, EF, etc. it probably doesn't matter - it's entirely possible that the TSQL translation will make it identical anyway. Of course, you can be sure that: -p

But for LINQ-to-Objects (which is very literal) this will be. You can improve this by using let:

return from c in ctx.Customers.Include("Addresses")
     let m = from a in c.Addresses where a.Nickname == "Me" select a
     where m.Any()
     let first = m.First()
     select new
     {
       Id = c.CustomerId,
       first.Name,
       first.Address1,
       ...
       first.PhoneNumber
     };
+11

Source: https://habr.com/ru/post/1705515/


All Articles