在 C# 列表容器中查找 and/or 访问值

Find and/or Access values in a C# List container

我确实找到了一些与此问题相关的解决方案,但它仍然不适合我。

我有一个整数数组列表 "numbers",其中有一些整数序列如下:

        List<int[]> numbers;
        numbers = new List<int[]>();
        numbers.Add(new int[] { 0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 14 }); // 0
        numbers.Add(new int[] { 1, 4, 7, 10, 13 }); // 1
        numbers.Add(new int[] { 0, 1, 2, 5, 6, 7, 8, 9, 12, 13, 14 }); // 2

然后,在处理一些数据后,我将得到一个目标序列 "MyList":

for (int i = 0; i < 5; i++ ){
                for(int j = 0; j < 3; j++){
                    if (TempImg.Data[i, j, 0] == 0)
                        MyList.Add(k);
                    k++;}}

然后,我想检查一下这个目标序列是否在我原来的列表中"numbers"。我首先将它转换为整数数组 "results" 如下:

int[] results = MyList.ToArray<int>();

然后倾向于在列表中找到它如下:

        k = numbers.IndexOf(results);
        Console.WriteLine(k);

输出是 (-1) 但不是匹配序列的实际索引。

-1 表示未找到,而当我将它显示到控制台时,我发现它是完全匹配的序列..我很想知道为什么它不起作用..

我也尝试这样做来迭代原始列表并找到匹配序列然后显示其索引。但也没有用:

        //for (int i = 0; i < numbers.Count(); i++)
        //{
        //    if (results == numbers[i])
        //        Console.WriteLine(i);
        //}

非常感谢

List<T>.IndexOf方法有什么作用?

Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.

包含相同元素的两个数组不是同一个对象。它们是两个完全不同的对象。 "hold" 这些数组的变量在程序的内存中有两个不同的引用。这些引用指向两个不同的位置。

您的问题的一种解决方法,可能是这样的:

var indexOfResults = -1;
for(var index=0; index<numbers.Size; i++)
{
    if(results.Length == numbers[index].Length 
       && results.Except(numbers[index]).Count() == 0)
    { 
        indexOfResults = index;
        break;
    }
} 

IndexOf中,两个数组作为引用进行比较,而不是作为值进行比较。这意味着由于数组位于内存中的不同位置,因此使用 IndexOf 方法进行比较时它们将不相等(即使它们的元素相等)。

您可以使用 Linq 中的 FindIndexSequenceEqual 方法找到索引:

numbers.FindIndex(collection => collection.SequenceEqual(results));

这将比较数组的元素和 return numbers 中第一个数组的索引与匹配元素。