2009-02-09 64 views
4

我有一個XElement,其中包含模擬數據的值。C#LINQ Where謂詞類型參數

我必須查詢XML的表達式:

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

中使用:

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

設計時間誤差是:

的類型參數方法「System.Linq的。 Enumerable.Where(System.Collections.Generic.IEnumerable,System.Func)'不能從用法中推斷出來。嘗試明確指定類型參數'

提供給Where的委託應該接受一個XElement並返回一個bool,標記該項是否與查詢匹配,我不知道如何向委託或where子句添加更多內容標記類型。

另外,針對實體框架的真實函數的並行方法沒有這個問題。什麼是不正確的LINQ到XML版本?

回答

10

不要使simpleXmlFunction成爲表達式< Func < XElement,bool > >。使它成爲Func < XElement,bool >。這是作爲一個代表的期望。在哪裏。

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

爲什麼它對Entity.Where工作? – blu 2009-02-09 19:22:07

3

我認爲,完整的答案包括以前的答案,大衛·莫頓的評論,更新的代碼片段:

的。凡實施IQueryable的比。凡實施IEnumerable的不同。 IEnumerable.Where預計一:

Func<XElement, bool> predicate 

您可以通過執行編譯從你的表情功能:

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

這將讓你看看生成的表達式樹,並使用編譯的形式查詢xml集合。