簡體   English   中英

C#-搜索特定數組的數組列表

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

我試圖找到可以解決問題的值的不同組合。 如果值(在雙精度數組中)通過測試,我想將它們添加到列表中,前提是它們尚未在列表中。

如果列表包含值[1、2、3、4、5]的數組,我檢查列表是否包含數組[5、4、3、2、1] List.Contains返回true。 無論如何,在數組順序很重要的地方搜索數組列表嗎?

我已經嘗試過List.Any(array.SequencyEqual),但這似乎有相同的問題。

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

如果if語句執行一次,則執行一次,然后再執行一次。

我怕你弄錯了, 運行這個簡單的測試程序

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

該程序輸出

False
True

正如我所期望的。

在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;
    }
}

現在,使用found來決定如何處理您的陣列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM