Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ Where Predicate Type Arguments

I have an XElement with values for mock data.

I have an expression to query the xml:

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

used in:

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

The design time error is:

The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly'

The delegate supplied to Where should take in an XElement and return a bool, marking if the item matches the query, I am not sure how to add anything more to the delegate or the where clause to mark the type.

Also, the parallel method for the real function against the Entity Framework does not have this issue. What is not correct with the LINQ-to-XML version?

like image 701
blu Avatar asked Dec 08 '22 08:12

blu


2 Answers

Don't make simpleXmlFunction an Expression<Func<XElement, bool>>. Make it a Func<XElement, bool>. That's what's expected as a delegate of .Where.

Func<XElement, bool> simpleXmlFunction =
     new Func<XElement, bool>(b => int.Parse(b.Element("FooId").Value) == 12);
like image 184
David Morton Avatar answered Dec 22 '22 19:12

David Morton


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 than the .Where implementation for IEnumerable. IEnumerable.Where expects a:

Func<XElement, bool> predicate

You can compile the function from the expression you have by doing:

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 look at the expression tree generated and to use the compiled form to query the xml collection.

like image 30
blu Avatar answered Dec 22 '22 19:12

blu