在列表中查找具有相同内容的字符串,避免字符串,其中搜索值是其他单词的合并部分

时间:2017-05-13 18:16:00

标签: c# string list linq contains

如何在列表string str = "three";中搜索List = new List<string> { "line one", "line two", "line three", "line four", "row three", "linethree", "three" };以获得此结果:

line three 
row three 
three

3 个答案:

答案 0 :(得分:1)

用空格拆分每个字符串,并检查是否有任何拆分字符串等于到目标字符串。这是代码:

var list = new List<string> { "line one", "line two", "line three", "line four", "row three", "linethree", "three" };

var result = list.Where(i => i.Split(' ').Any(j => j.Equals("three"))).ToList();

//result:
//    line three 
//    row three 
//    three

在您正在寻找不区分大小写的解决方案的情况下,您可能还希望使用StringComparison.InvariantCultureIgnoreCase作为Equals方法的第二个参数。

答案 1 :(得分:0)

在三个中的第一个中添加空格,如下所示:

string str = " three"

所以它只是得到了文字

以及像这样的更新输入使用

string str = " "+"three"

答案 2 :(得分:0)

str转换为正则表达式,方法是在开头和结尾添加\ b以查找单词,然后使用Regex.Match选择匹配项。