Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# comparing arrays

Tags:

c#

list

linq

good afternoon everybody

the question is kinda simple but I've been having problems the whole afternoon

i have 2 lists:

  • list of ints (ids)
  • list of objects (that contains ids)

and i want to compare them but i want to obtain the id that doesn't have a pair (if it exists)

i was wondering if there's a c# or linq method to identify the values that are different 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 was trying something like

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

but like you can imagine it doesn't work

for example

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

the ids are different when i compare them so i get a bigger list that the one i need

i also tried with an linq outer join but i don't understand how it works pretty well

like image 422
Carlos Guillermo Bolaños Lopez Avatar asked Nov 30 '22 16:11

Carlos Guillermo Bolaños Lopez


2 Answers

var idsWithoutObjects = ids.Except(x.Select(item => item.id));
like image 105
Anthony Pegram Avatar answered Dec 11 '22 08:12

Anthony Pegram


What you are after is the Except extension method. It gives you the set difference between two sequences.

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

var idDifferences = x.Select(item => item.id).Except(ids);
like image 23
Rune Grimstad Avatar answered Dec 11 '22 10:12

Rune Grimstad