【问题标题】:How to search a list in C#如何在 C# 中搜索列表
【发布时间】:2011-03-27 17:47:56
【问题描述】:

我有一个这样的列表:

List<string[]> countryList

字符串数组的每个元素都是另一个包含 3 个元素的数组。

所以countryList[0] 可能包含数组:

new string[3] { "GB", "United Kingdom", "United Kingdom" };

如何在 countryList 中搜索特定数组,例如如何搜索countryList

new string[3] { "GB", "United Kingdom", "United Kingdom" }?

【问题讨论】:

    标签: c# arrays search


    【解决方案1】:
    return countryList.FirstOrDefault(array => array.SequenceEqual(arrayToCompare));
    

    要简单地建立存在,请使用countryList.Any。 要查找元素的索引,如果不存在则为 -1,请使用 countryList.FindIndex

    【讨论】:

    • 我错过了什么,因为我的 List 对象上没有 FirstOrDefault 方法,我有一个 Find 和 FindAll。而且我没有SequenceEqual。我正在使用 .NET 3.5
    • 啊,我没有导入 system.linq ... ups!
    【解决方案2】:
    // this returns the index for the matched array, if no suitable array found, return -1
    
    public static intFindIndex(List<string[]> allString, string[] string)
    {
        return allString.FindIndex(pt=>IsStringEqual(pt, string));
    }
    
    
     private static bool IsStringEqual(string[] str1, string[] str2)
    {
       if(str1.Length!=str2.Length)
          return false;
       // do element by element comparison here
       for(int i=0; i< str1.Length; i++)
       {
          if(str1[i]!=str2[i])
             return false;
       }
       return true;
    }
    

    【讨论】:

    • 错误... Equals 方法比较的是引用而不是数组中的值,所以它永远找不到任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多