[英]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.