How to check if at least one item is different comparing two lists?

Viewed 303

Suppose that I've two list:

foo1<T>
foo2<T>

each list have as property Id that's an int, I need to check if all the ids of list foo1 are equal to list foo2, what I did:

foo1.Where(x => foo2.Any(z => z.Id != x.Id)).Any();

so essentially if all Ids value of each item are equal should return false, if almost one is different should return true. Both list are already ordered.

Actually i get even true, but it should return false 'cause all my items Ids are equal.

What am I doing wrong?

Thanks.

4 Answers

You can use All and Any Linq extension methods.

Please have a look on this approach:

var result = !foo1.All(x => foo2.Any(y => y.Id == x.Id));

You could use SequenceEqual for this:

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

Here's how that looks with your code and requirements:

!foo1.Select(x => x.Id).SequenceEqual(foo2.Select(x => x.Id));

Simplest way ^^

List<Foo> foo1 = new List<Foo>();
List<Foo> foo2 = new List<Foo>();
foo1.Add(new Foo(1));
foo2.Add(new Foo(1));
bool equal = foo2.All(x => x.Id == foo1.FirstOrDefault()?.Id);

You need to include index also as you are comparing every two elements

foo1.Where((x, index) => foo2.Any((z, index1) => z.Id != x.Id && index == index1)).Any();
Related