1

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 and accepted for providing both versions. I decided to go with the LINQ Expression syntax for clarity reasons
3

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;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.