包含无顺序

Contains without order

我想使用一组字符搜索字符串列表,并希望找到匹配项而不考虑顺序。例如,如果我的列表包含

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

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

你可以使用 linq 来实现这个

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

确保你也比较了使用 ToUpper 的情况,你想比较的 string 也使它成为 UpperCase

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

为此,您可以这样做:

    // 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));
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

中的所有字母

如果您不关心匹配重复项而不是检查您正在搜索的序列中的所有字符是否都包含在谓词中,则可以这样做:

 "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,然后手动执行 except 操作。
  • 如果您需要多次针对同一个列表匹配不同的值 - 将字符串列表转换为 HashSet 列表并使用 search.All(c => wordAsHashSet.Contains(c)) 作为条件。