Search code examples
c#entity-frameworklambdaexpression-trees

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?


Solution

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