如何比较数组和数组列表 [英] how to compare list of array and array

查看:123
本文介绍了如何比较数组和数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态列表< int [,]> list = new List< int [,]>();

int [,] array = {{1,1},{2,2}};

list.Add(array);



foreach(列表中的var元素)

if(element == array)// return -1 !!!!!!为什么?????

{

//

}

static List<int[,]> list = new List<int[,]>();
int[,] array={{1,1},{2,2}};
list.Add(array);

foreach(var element in list)
if(element==array)//return -1!!!!!! why?????
{
//
}

推荐答案

您可以使用SequenceEqual。这适用于任何IEnumerable< t>,而不仅仅是数组
You could use SequenceEqual. This works for any IEnumerable<t>, not just arrays


您的代码将按原样运行。



请保留请注意原因它的作用是因为你正在比较价值类型... Ints ...不是参考类型!



这里我是使用您使用的相同比较,我刚刚打包成一个函数:
Your code will work as it is.

Do keep in mind that the reason it works is because you are comparing Value Types ... Ints ... not Reference Types !

here I am using the same comparison that you use, I've just packaged into a function:
static List<int[,]> list = new List<int[,]>();
int[,] array={{1,1},{2,2}};

public bool isInArray(List<int[,]> list1, int[,] array)
{
    foreach (var subArray in list1)
    {
        if (subArray == array)
        {
            return true;
        }
    }

    return false;
}

// test in some method or EventHandler:

list.Add(array);

bool test = isInArray(list, array);


这篇关于如何比较数组和数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆