Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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
Posted

Hi, well the easiest way that comes to my mind is to do it with a LINQ like this:
C#
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.
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 16-Apr-15 4:10am    
Correct, LINQ introduces a lot of functions easier to handle. +5
Mario Z 16-Apr-15 4:13am    
True, it makes our life a lot easier that is for sure and code is a lot more readable.
Also thank you :)
Praveen Kumar Upadhyay 16-Apr-15 4:21am    
+5. Nice
 
Share this answer
 
v2
Comments
Shrikesh_kale 16-Apr-15 4:00am    
how to get non matching element
Black_Rose 16-Apr-15 4:04am    
Check the updated asnwer..
Use Linq concept...

C#
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;
        }
    }
}
 
Share this answer
 
v3
Comments
Shrikesh_kale 16-Apr-15 4:00am    
how to Extracting non matching vaues
Praveen Kumar Upadhyay 16-Apr-15 4:03am    
This is not Linq.
Afzaal Ahmad Zeeshan 16-Apr-15 4:10am    
But LINQ concept; HasDuplicate.
Praveen Kumar Upadhyay 16-Apr-15 4:20am    
Do you think, just by adding a variable named 'hasDuplicate' makes your code a Linq code?
Afzaal Ahmad Zeeshan 16-Apr-15 4:34am    
No I am not saying it became LINQ code, it has same concept. Do you know the different between being actual and conceptual?
Use Enumerable.SequenceEqual method:

C#
int [] n = new int [6] {1,2,3,4,5,6};
int [] m = new int [3] {1,5,6};
bool result = n.SequenceEqual(m);
 
Share this answer
 
Comments
Praveen Kumar Upadhyay 16-Apr-15 4:02am    
But this is not returning non matching elements.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900