【发布时间】:2011-06-06 20:25:12
【问题描述】:
Linq to XML 中 where 子句的 .Contains() 函数出现意外行为。它的功能似乎类似于字符串函数中的“==”not Contains()。
例子:
var q = from sr in SearchResults.Descendants("Result")
where _filters.Contains((string)sr.Element("itemtype"))
orderby (string)sr.Element("ipitemtype") ascending
select new SearchItem
{
//Create Object
ID = (string)sr.Element("blabla"),
}
_filters 是一个字符串列表。假设它包含 3 个值:
_filters[0] = "videos";
_filters[1] = "documents";
_filters[2] = "cat pictures";
现在发生的情况是,如果 Query 完美运行
<itemtype>videos</itemtype>
是 XML 节点。
但是,如果节点是
<itemtype>videos mission critical document advertising</itemtype>,
IEnumerable 返回空白,这对我来说表示操作数的功能类似于“==”而不是“Contains()”。
知道我做错了什么吗?
来自 dtb 的获奖答案:
替换
where _filters.Contains((string)sr.Element("itemtype"))
与
where _filters.Any(filter => ((string)sr.Element("itemtype")).Contains(filter))
【问题讨论】:
-
请检查我的新答案 - 原来的答案是错误的。
标签: c# .net linq-to-xml