我有一個帶有模擬數據值的XElement。
我有一個表達式來查詢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-to-XML版本有什麼不正確之處?
不要將simpleXmlFunction設為Expression <Func <XElement,bool >>。使它成為Func <XElement,bool>。這就是.Where的代表所期待的。
Func<XElement, bool> simpleXmlFunction =
new Func<XElement, bool>(b => int.Parse(b.Element("FooId").Value) == 12);
我認為完整的答案包括之前的答案,David Morton的評論和更新的代碼片段:
IQueryable的實現與IEnumerable的.Where實現不同。 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集合。