4

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

1
  • 1
    if (item.id != id) idDiferentes.Add(id), and please don't use "u" instead of "you" and "i" instead of "I". Commented May 20, 2011 at 20:05

5 Answers 5

10
var idsWithoutObjects = ids.Except(x.Select(item => item.id));
Sign up to request clarification or add additional context in comments.

Comments

7

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);

Comments

3

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.

Comments

1

As an alternative to LINQ (although LINQ is probably the right answer here), if all your ids are unique you may be able to use the Contains() method, for example:

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

Comments

0

It is easier to use a flag, e.g.:

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);
}

2 Comments

this would not compile. Among other issues, you have the if (!b) outside of the outer foreach, and id is no longer in scope.
Excelent Guys Thank you very much for your help, thanks to you i could solve my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.