C # array comparison

Good day to all

The question is simple, but I had problems all day.

I have 2 lists:

  • list of ints (ids)
  • list of objects (containing identifiers)

and I want to compare them, but I want to get an id that does not have a pair (if it exists)

I was wondering if there is a C # or linq method for determining values ​​that differ in two arrays

Example

if I have

List<int> ids = {1,2,3,4,5} 

and

 List<objectX> x = (contains id,code, and description) 

and I tried something like

 foreach (int id in ids) { foreach (objectX item in x) { if (item.id == id) { break; } else idDiferentes.Add(id); } } 

but as you can imagine, it does not work.

eg

 ids= {1,2,3,4} objectx[id] ={1,3,2} 

Ides are different when I compare them, so I get a larger list that I need

I also tried with an external linq connection, but I don't understand how this works very well

+4
source share
5 answers
 var idsWithoutObjects = ids.Except(x.Select(item => item.id)); 
+10
source

Why do you need it Except for the extension method. This gives you the given difference between the two sequences.

So you can do something like this (pseudo C # -code):

 var idDifferences = x.Select(item => item.id).Except(ids); 
+7
source

Linq Set Operations:

 int[] A = { 1 , 2 , 3 , 4 , 5 , } ; int[] B = { 2 , 3 , 4 , 5 , 6 , } ; int[] A_NotIn_B = A.Except( B ).ToArray() ; int[] B_NotIn_A = B.Except( A ).ToArray() ; 

There you go.

+3
source

As an alternative to LINQ (although LINQ is probably the correct answer here), if all your identifiers are unique, you can use the Contains() method, for example:

 foreach(objectX item in x) { if(!ids.Contains(item.id)) { idDiferentes.Add(item.id); } } 
+1
source

It is easier to use a flag, for example:

 bool b = False; foreach (int id in ids) { foreach (objectX item in x) { if (item.id == id) { b = True; break; } } } if (!b) { idDiferentes.Add(id); } 
0
source

All Articles