简体   繁体   中英

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?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM