如何在C#中比较数组 [英] how to compare array in C#

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

问题描述

如何比较数组



我必须数组



int [] n = new int [6] {1,2,3,4,5,6};



int [] m = new int [3] {1,5,6} ;



我想比较数组和提取不匹配的值。



怎么可能。



先谢谢

解决方案

我想到的最简单方法就是做使用这样的LINQ:

  int  [] nonMatching = n.Except(m).Union (m.Except(n))。ToArray(); 



简而言之 n.Except(m)返回 n m 数组中找不到的数组项, m.Except(n)反之亦然联盟会将这两者合并为一个集合。

另一种方法是使用嵌套的foreach并检查每个 n 数组的项目,每个 m 数组的项目。

查看此similer讨论



比较 - 两个阵列-c-sharp [ ^ ]



比较两阵列或 - 的ArrayLists找到的相似和 - 不同值 [ ^ ]



希望它会有所帮助。


使用Linq概念...



  bool  hasDuplicate =  false ; 
int [] a = new int [] { 1 2 3 4 5 6 };
int [] b = new int [] { 1 5 6 };
foreach var numberA in a)
{
foreach var numberB in b)
{
if (numberA == numberB)
{
hasDuplicate = true ;
}
}
}


How to Compare Array

I have to Array

int [] n= new int [6] {1,2,3,4,5,6};

int [] m= new int [3] {1,5,6};

I want to compare both array and extracting non matching values .

how it is possible.

Thanks in Advance

解决方案

Hi, well the easiest way that comes to my mind is to do it with a LINQ like this:

int[] nonMatching = n.Except(m).Union(m.Except(n)).ToArray();


In short the n.Except(m) returns n array's items that are not found in m array, m.Except(n) does the vice versa and the Union will combine those two into a single collection.
Another way would be to just use a nested foreach and check each n array's item with each m array's item.


Check this similer discussion

comparing-two-arrays-in-c-sharp[^]

compare-two-arrays-or-arraylists-find-similar-and-different-values[^]

Hope it will help.


Use Linq concept...

bool hasDuplicate = false;
int[] a = new int[] {1,2,3,4,5,6 };
int[] b = new int[] { 1,5,6 };
foreach (var numberA in a)
{
    foreach (var numberB in b)
    {
        if (numberA == numberB)
        {
            hasDuplicate = true;
        }
    }
}


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

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