我试图在我的数据库中找到一个项目可能会或可能不会在其标题中包含特定单词,方法是在一个单词数组上运行循环。我知道如何在查询中循环绝对包含但我不想这样做。这是我的代码:
C#
var item = "the-batman-returns-hd-version";
var id = 0;
//split slug by dash into an array
var keywords = item.Split('-'); //gives me (the, batman, returns, hd, version)
//remove any work less than 4 chracters
var result = _contentService.Products;
foreach (var word in keywords )
{
if (word.Length <= 4) continue;
var key = word;
result = result.Where(c => c.Title.Contains(key));
}
var firstOrDefault = result.FirstOrDefault();
if (firstOrDefault != null)
{
id = firstOrDefault.Id;
}
//loop query to search where all parts exist
return (id);
以上作品。但该产品被称为“蝙蝠侠归来”,因此它返回0,因为它无法找到任何包含“hd”和“version”的项目。
无论如何都是OR循环的linq。如:
foreach (var word in keywords )
{
if (word.Length <= 4) continue;
var key = word;
result = result.Where(c => c.Title.Contains(key) ||); //or; then loop again.
}
答案 0 :(得分:4)
您可以使用.Any()
方法:
result = result.Where(c => keywords.Any(k => c.Title.Contains(k)));
您可以进一步过滤少于5个字符的单词,如您所希望的那样:
result = result.Where(c => keywords.Where(k => k.Length > 4).Any(k => c.Title.Contains(k)));
虽然在构建关键字数组时执行一次会更有效:
var keywords = item.Split('-').Where(k => k.Length > 4).ToArray();