Saket Kumar
Saket Kumar

Reputation: 4825

Check if each object of list is present in another list

I have two lists of same class:

class Test
{
int A;
String B;
Char C;
}

Element of two lists are:

List<Test> obj1 :

1   “Abc”   'a'
2   “Bcd”   'b'

List<Test> obj2:

1   “Abc”   'a'
2   “Bcd”   'b'
3   “Cde”   'c'
4   “Def”   'd'
5   “Efg”   'e'

I want to check if rows of obj1 is present in obj2. For example first two rows of obj1 is in obj2. I have achieved this using loops. Can anyone help me in doing the same through linq query or without loops. Any help will be appreciated.

Upvotes: 1

Views: 174

Answers (2)

gleng
gleng

Reputation: 6304

If your lists share the same instances of objects (you can see @lazyberezovsky's post for overriding Equals and GetHashCode methods) you can use LINQ Any. This will return true if an item in obj1 is in obj2:

obj1.Any(obj => obj2.Contains(obj));

EDIT

If I misunderstood you (as some commenters suggested) and you want to check if all objects in obj1 are present in obj2 you can use LINQ All. This will return true if all items in obj1 are present in obj2:

obj1.All(obj => obj2.Contains(obj));

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

If you don't want to override Equals and GetHashCode, or create custom comparer for your objects, then you can project both lists into anonymous objects:

obj1.Select(t => new { t.A, t.B, t.C })
    .Except(obj2.Select(t => new { t.A, t.B, t.C })
    .Any();

If your lists share same instances of objects, then simply (it will compare objects by references)

obj1.Except(obj2).Any()

You can use this approach if you will add Equals and GetHashCode implementations to your class (see sample of implementation below). Also you can create comparer for your test classes:

public class TestComparer : IEqualityComparer<Test>
{
    public bool Equals(Test x, Test y)
    {
        return (x.A == y.A) && (x.B == y.B) && (x.C == y.C);
    }

    public int GetHashCode(Test obj)
    {
        int hash = 19;
        hash = hash * 17 + obj.A.GetHashCode();
        hash = hash * 17 + obj.B.GetHashCode();
        hash = hash * 17 + obj.C.GetHashCode();
        return hash;
    }
}

And pass this comparer to overloaded Except method:

obj1.Except(obj2, new TestComparer()).Any()

Upvotes: 3

Related Questions