tags:

views:

66

answers:

1

I have a LINQ statement where I'd like to merge in the First address with the Nickname of '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'm wondering:

  1. Is it going to hurt performance if I call First multiple times like this?
  2. Is there an better LINQ statement for this?
  3. Just also realized, Do I need to .Include("Addresses")?
+5  A: 

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

But for LINQ-to-Objects (which is very literal) it will. 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
     };
Marc Gravell
by that note, can I just let me = c.Addresses.FirstOrDefault(a.Nickname == "Me")?
bendewey
then compare where me != null
bendewey
Also just for the record I'm using LINQ to EF
bendewey
With EF, you can try various layouts - see which gives TSQL you are happiest with.
Marc Gravell