2017-02-17 70 views
1

我想使用一组字符来搜索字符串列表,并希望查找匹配,而不管顺序如何。例如,如果我的列表包含包含无订单

List<string> testList = new List<string>() { "can", "rock", "bird" }; 

我希望能够使用“irb”进行搜索并让它返回鸟。我必须多次这样做,所以我正在寻找最有效的方法。

回答

4
var query = "irb"; 
List<string> testList = new List<string>() { "can", "rock", "bird" }; 

var result = testList.Where(i => query.All(q => i.Contains(q))); 

对于在testList测试每一项,看它是否包含在query

0

您可以使用LINQ来实现这一

List<string> testList = new List<string>() { "can", "rock", "bird" }; 
var lst = testList.Where(x => x.ToUpperInvariant().Contains("IRD")).ToList(); 

请确保您还使用ToUpper比较案件和string你想也比较让它UpperCase

+0

这只会发现如果字母的顺序与搜索词中出现的顺序相同。我想说输入或带回岩石 – jsomers89

+0

我想你必须搜索使用配对。 – Mairaj

+0

@ jsomers89只有一件事情会出现匹配词。我的意思是如何匹配单词'或'或单词也可以像'rk'一样出现? – Mairaj

1

对于您的情况,您需要检查单词的每个字符在另一个单词列表中。

对于这一点,你可以这样做:

// Checks whether all character in word is present in another word 
    Func<string, string, bool> isContain = (s1, s2) => 
    { 
     int matchingLength = 0; 
     foreach (var c2 in s2.ToCharArray()) 
     { 
      foreach (var c1 in s1.ToCharArray()) 
      { 
       if (c1 == c2) 
        ++matchingLength; 
      } 
     } 

     // if matched length is equal to word length given, it would be assumed as matched 
     return s2.Length == matchingLength; 
    }; 

    List<string> testList = new List<string>() { "can", "rock", "bird" }; 
    string name = "irb"; 
    var fileredList = testList.Where(x => isContain(x, name)); 
1

所有的信件如果你不在乎关于匹配重复项而不是检查您搜索的序列中的所有字符是否包含在该单词中都会用于谓词:

"irb".Except("bird").Count() == 0 

而且整体条件:

List<string> testList = new List<string>() { "can", "rock", "bird" }; 
    var search = "irb"; 
    var matches = testList.Where(word => !search.Except(word).Any()); 

注:

  • 需要规范所有的话,如果你需要混合大小写字母相匹配为小写。
  • 如果搜索不同值的性能很关键 - 首先将搜索字符串转换为HashSet,然后手动执行。
  • 如果您需要多次匹配相同列表的不同值 - 将字符串列表转换为HashSet列表,并使用search.All(c => wordAsHashSet.Contains(c))作为条件。