views:

694

answers:

3

I was wondering if it is possible to include inner variables or delegates in linq statements?

I currently am using Linq to XML with XPath extensions and am using a where clause on an element that I cannot guarantee will exist.

Here is a sample of what I mean:

var result =
    from record in xml.Root.XPathSelectElements("record")
    where ...
    select record;

I want the where to be something like:

where 
{ 
    var element = record.XPathSelectElement("element[@type='sometype']"); 
    return (element != null && element.Value.Contains("keyword")); 
}
+6  A: 

You want the "let" keyword in Linq. Something like this?

var result =
    from record in xml.Root.XPathSelectElements("record")
    let element = record.XPathSelectElement("element[@type='sometype']")
    where (element != null && element.Value.Contains("keyword"))
    select record;
Ken
+1  A: 

I don't know the query syntax well enough to say for sure, but this would be trivial with the functional syntax:

var result = xml.Root.XPathSelectElements("record").Where(record => {
   var element = record.XPathSelectElement("element[@type='sometype']");
   return (element != null && element.Value.Contains("keyword"));
});
mquander
+2  A: 

You could use a "let" clause here;

from record in xml.Root.XPathSelectElements("record")
let element = record.XPathSelectElement("element[@type='sometype']")
where element != null && element.Value.Contains("keyword")
select record;
Chris Shaffer