tags:

views:

29

answers:

3

take this linq into consideration:

list.Where(sil => sil.XML.Element("ticket") != null && sil.XML.Element("ticket").Attribute("id").Value == smsRequestIn.TicketID)

if the "ticket" element is not null it searches for it twice and hence is not very effective. Is there a way to use some sort of variables within the linq expression so I can reference the variable instead of doing a double search for the "ticket" element or is linq intelligent enough to not do a double search?

+4  A: 

In LINQ Expression syntax you'd use let like this:

from sil in list
let ticket = sil.XML.Element("ticket")
where ticket != null && ticket.Attribute("id").Value == smsRequestIn.TicketID
select sil;

To replicate let using extension methods, you need to use Select and an anonymous type like so

list.Select(anon => new { ticket = anon.XML.Element("ticket"), anon })
    .Where(sil => sil.ticket != null && sil.ticket.Attribute("id").Value == smsRequestIn.TicketID)
    .Select(o=>o.anon);

Which is abundantly less clear.

Jason Punyon
+1 and accepted for providing both versions. I decided to go with the LINQ Expression syntax for clarity reasons
Jonas Stawski
+3  A: 

I'd rewrite your query to the following:

var result = from sil in list
             let element = sil.XML.Element("ticket")
             where element != null &&
                   element.Attribute("id").Value == smsRequestIn.TicketID
             select sil;
Ronald Wildenberg
A: 

You can do something like this:

Func<SilClass,bool> filter = sil => 
{ 
   XElement e = sil.XML.Element("ticket");
   return e != null && e.Attribute("id").Value == smsRequestIn.TicketID);
};

list.Where(filter);

but in this case I think you really benefit in using query syntax like other answers have suggested. It's much more clear.

bruno conde