简体   繁体   English

C#-搜索特定数组的数组列表

[英]C# - Search list of arrays for specific array

I am trying to find different combinations of values that will solve a solution. 我试图找到可以解决问题的值的不同组合。 If the values (in a double array) pass a test I want to add them to a list, providing they are not already in the list. 如果值(在双精度数组中)通过测试,我想将它们添加到列表中,前提是它们尚未在列表中。

If the list contains an array with values [1, 2, 3, 4, 5] and I check to see if the list contains array [5, 4, 3, 2, 1] List.Contains returns true. 如果列表包含值[1、2、3、4、5]的数组,我检查列表是否包含数组[5、4、3、2、1] List.Contains返回true。 Is there anyway to search a list of arrays where order of the array matters? 无论如何,在数组顺序很重要的地方搜索数组列表吗?

I have tried List.Any(array.SequencyEqual) but that seems to have the same issue. 我已经尝试过List.Any(array.SequencyEqual),但这似乎有相同的问题。

if(!myList.Any( a => a.SequenceEqual(myArray)))
{
    //some code to print array values 
    myList.Add(myArray);
}

This if statement executes true once, then never again. 如果if语句执行一次,则执行一次,然后再执行一次。

I fear you are mistaken, run this simple test program 我怕你弄错了, 运行这个简单的测试程序

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var list = new List<double[]>
            {
                new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }
            };
        Console.WriteLine(
            list.Any(a => a.SequenceEqual(new[] { 5.0, 4.0, 3.0, 2.0, 1.0 })));
        Console.WriteLine(
            list.Any(a => a.SequenceEqual(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 })));
    }
}

this program outputs 该程序输出

False
True

as I would expect. 正如我所期望的。

There's probably a fancy way to do this in LINQ, but here's the old fashioned way... 在LINQ中可能有一种花哨的方法可以做到这一点,但这是老式的方法。

List<int[]> list = new List<int[]>();
int[] array1 = new int[]{ 1, 2, 3, 4, 5 };
int[] array2 = new int[]{ 5, 4, 3, 2, 1 };
list.Add(array1);
// add other arrays to list
bool found = false;
foreach (int[] other in list)
{
    bool isMatch = true;
    if (array2.Length == other.Length)
    {
        for (int i = 0; i < array2.Length; i++)
        {
            if (array2[i] != other[i])
            {
                isMatch = false;
                break;
            }
        }
    }
    else
    {
        isMatch = false;
    }

    if (isMatch)
    {
        found = true;
        break;
    }
}

Now, use found to decide what to do with your array. 现在,使用found来决定如何处理您的阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM