使用精确Word的LINQ过滤列表

时间:2013-03-21 01:34:15

标签: c# linq

我有这个字符串列表。我想过滤掉那些与我搜索过的关键字完全匹配的项目。例如,我有关键字“in”我希望结果只过滤那些具有确切单词“in”的项目。请帮忙。

代码

static IEnumerable<string> GetData()
       {
           var strList = new List<string> 
           { "I'm in love",
            "Coffee contains caffeine",
            "The best inn so far",
            "Inside of me",
            "in the darkness"};
           var filteredItems = strList.Where(x => x.Contains("in"));
           return filteredItems;
       }

从我的列表中我只想返回第1项和第5项,因为它们是具有确切单词“in”的项目。

enter image description here

3 个答案:

答案 0 :(得分:5)

这是一种方法:

var filteredItems = strList.Where(x => (" " + x + " ").Contains(" in "));

或者这个:

var filteredItems = strList.Where(x => Regex.IsMatch(x, "(^| )in($| )"));

不区分大小写的版本:

var filteredItems = strList.Where(x => (" " + x .ToLower() + " ").Contains(" in "));
var filteredItems = strList.Where(x => Regex.IsMatch(x, "(^|\s)in($|\s)",
                                                     RegexOptions.IgnoreCase));

答案 1 :(得分:2)

我希望使用Regex.IsMatch方法。例如:

string pattern = "<your pattern here>";

static IEnumerable<string> GetData()
   {
       var strList = new List<string> 
       { "I'm in love",
        "Coffee contains caffeine",
        "The best inn so far",
        "Inside of me",
        "in the darkness"};
       var filteredItems = strList.Where(x => Regex.IsMatch(x, pattern));
       return filteredItems;
   }

应该匹配的模式是:^(.*)\sin\s(.*)$

零个或多个字符,然后是“in”(即由空格包围),然后是零个或多个字符。您可以使用类似Rubular的内容或网上的其他许多内容来测试您的正则表达式,以确保您获得正确的里程: - )

脸颊上略显舌头,但正则表达式可能会给你更多problems: - )

HTH,Nathan

答案 2 :(得分:1)

正确的方法是构建一个正则表达式。

这样做的便宜方法,在字符串的正面和背面添加空格,以匹配正在寻找的单词,正面和背面有空格:

static IEnumerable<string> GetData(string match)
   {
       var strList = new List<string> 
       { "I'm in love",
        "Coffee contains caffeine",
        "The best inn so far",
        "Inside of me",
        "in the darkness"};

       match = match.ToLower(); //to do case insensitive matching
       var filteredItems = strList.Where(x => (" " +x.ToLower() + " ").Contains(" "+match+" "));
       return filteredItems;
   }