C # LINQ Where Predicate Type Arguments

I have an XElement with values ​​for mock data.

I have an expression for an xml request:

Expression<Func<XElement, bool>> simpleXmlFunction = b => int.Parse(b.Element("FooId").Value) == 12; 

used in:

 var simpleXml = xml.Elements("Foo").Where(simpleXmlFunction).First(); 

Development Time Error:

Type arguments to the 'System.Linq.Enumerable.Where (System.Collections.Generic.IEnumerable, System.Func)' method cannot be taken out of use. Try explicitly specifying type arguments

The delegate provided in Where should take an XElement and return a bool, noting whether the element matches the request, I'm not sure how to add anything else to the delegate or to the where clause to mark the type.

In addition, the parallel method for a real function in relation to the Entity Framework does not have this problem. What doesn't match the LINQ-to-XML version?

+4
source share
2 answers

Do not do simpleXmlFunction Expression <Func <XElement, bool β†’. Make it Func <XElement, bool>. This is what is expected as a delegate. Where.

 Func<XElement, bool> simpleXmlFunction = new Func<XElement, bool>(b => int.Parse(b.Element("FooId").Value) == 12); 
+10
source

I think the full answer includes the previous answer, David Morton's comment, and an updated code snippet:

The .Where implementation for IQueryable is different from the .Where implementation for IEnumerable. IEnumerable.Where expects:

 Func<XElement, bool> predicate 

You can compile a function from an expression that you have:

 Expression<Func<XElement, bool>> simpleXmlExpression = b => int.Parse(b.Element("FooId").Value) == 12; Func<XElement, bool> simpleXmlFunction = simpleXmlExpression.Compile(); var simpleXml = xml.Elements("Foo").Where(simpleXmlFunction).First(); 

This will allow you to view the generated expression tree and use the compiled form to query the xml collection.

+3
source

All Articles