我正在尝试查询xml文件中的两个属性,以查找搜索词。
我有这个:
<?xml version="1.0" encoding="utf-8" ?>
<Products>
<item ProductName="Golf Shirt" Content="This is a nice breathable shirt for golf." />
<item ProductName="Bowling Ball" Content="This is a colorful 8-lbs ball." />
<item ProdcutName="Tee Shirt" Content="100% cotton tee-shirt." />
</Products>我想查询搜索词的ProductName和Content属性值。
下面是我的查询表达式:
var results = from node in _xDoc.Descendants("Item")
where node.Attribute("Content").Value.Contains(searchTerm)
where node.Attribute("ProductName").Value.Contains(searchTerm)
select new SearchModel()
{
Name = node.Attribute("ProductName").Value,
Url = "the url",
Group = "Products"
};如果我的搜索词是“衬衫”,我应该返回“高尔夫衬衫”和“T恤”,但我什么也得不到。我认为这是因为双"where“子句创建的是and " and”表达式,而我需要一个"or“表达式。如果我删除其中一个"where“子句,它就会起作用。
我尝试将"||“放在第一个"where”子句之后,但这会产生错误。
如何实现Linq- to -Xml的"or where“子句?
谢谢。
发布于 2012-06-08 06:48:43
你有没有尝试过这样的东西:
where ((string)node.Attribute("Content")).Contains(searchTerm) || ((string)node.Attribute("ProductName")).Contains(searchTerm)发布于 2012-06-08 07:03:33
我想通了。这是我的解决办法。
var results = _xDoc.Descendants("Item")
.Where(c =>
(
c.Attribute("ProductName").Value.ToLower().Contains(searchTerm.ToLower()) ||
c.Attribute("Content").Value.ToLower().Contains(searchTerm.ToLower())
)
)
.Select(c => new SearchModel()
{
Name = c.Attribute("ProductName").Value,
Url = "the url",
Group = "Products"
});https://stackoverflow.com/questions/10940874
复制相似问题