如何在LINQ中搜索整个单词?
如果我在字符串{"carpenter","car repair","carrying","car workshop"}
等列表中搜索单词“car”,结果应该是“汽车修理”& “汽车车间”只。
我尝试下面的代码
List<string> _tags = (from item in string_array
where item.ToLower().Contains(search_term)
select item).ToList();
但是,包含总是返回相似的字词,我在SO Linq Regex for whole word search上找到了此链接 这并没有使用Regx提供完整的答案。
因此,任何人都可以帮助在Regx中写一个答案,或者是Linq使用的任何其他选项。
答案 0 :(得分:17)
试试这个:
var result = items.Where(i => i.Split(' ').Any(word => word.ToLower() == "car")).ToList();
如果您需要考虑逗号,可以改用:
var reg = new Regex("\\bcar\\b", RegexOptions.IgnoreCase);
var items = new [] { "carpenter", "car repair", "carrying", "car workshop", "car, repair", "car. repair", "car,repair" };
var result = items.Where(word => reg.IsMatch(word)).ToList();
给出:
car repair
car workshop
car, repair
car. repair
car,repair
答案 1 :(得分:2)
list.Where(item=>item.Split(' ').Contains("car"));
答案 2 :(得分:2)
您可以执行以下操作:
string.Split()
Contains
overload StringComaparer
搜索单词
像:
string[] string_array = {"carpenter", "car repair", "carrying", "car workshop"};
string word = "car";
List<string> _tags = string_array.Where(r => r.Split()
.Contains(word, StringComparer.InvariantCultureIgnoreCase))
.ToList();
输出:
foreach (var item in _tags)
{
Console.WriteLine(item);
}
输出将是:
car repair
car workshop
答案 3 :(得分:1)
我只是在搜索关键字之前和之后寻找空格。
List<string> _tags = string_array.Where(
s => s.ToUpper().Contains(" " + search_term.ToUpper()) ||
sToUpper().Contains(search_term.ToUpper() + " ") || s.ToUpper == search_term.ToUpper()).ToList();
答案 4 :(得分:1)
var strResult = strings.Where(x => x.Split(' ').Any(y => y.Equals("car"))).ToList();