Where Predicate Type Arguments in C#

c# entity-framework expression-trees lambda

Question

I have an XElement with dummy data values.

I have a formula to search the xml:

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

uses in

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

This is the design time error:

the parameters of type "System.Linq.Enumerable" for method. It is impossible to conclude from use where(System.Collections.Generic.IEnumerable, System.Func)'. Try explicitly stating the type parameters.

I'm not sure how to add anything else to the delegate or the where clause to signal the type. The delegate provided to Where should take in an XElement and return a bool, indicating whether the item fits the query.

Additionally, this problem is not present in the parallel technique for the actual function against the Entity Framework. What about the LINQ-to-XML version is incorrect?

1
4
4/19/2009 7:27:29 AM

Accepted Answer

SimpleXmlFunction shouldn't be an ExpressionFuncXElement, bool>>. Create a FuncXElement, bool> for it. As a delegate, it is what is required of you. Where.

Func<XElement, bool> simpleXmlFunction =
     new Func<XElement, bool>(b => int.Parse(b.Element("FooId").Value) == 12);
11
2/9/2009 6:16:19 PM

Popular Answer

The preceding response, David Morton's observation, and a modified code snippet, in my opinion, make up the whole response:

IQueryable's.Where implementation differs from the.Where implementation. implementation of IEnumerable where. IEnumerable. When to anticipate a:

Func<XElement, bool> predicate

You may create a function from an expression by doing the following:

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 enable you to see the expression tree that was built and query the xml collection using the compiled form.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow