Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 871
jode Avatar asked Dec 13 '22 19:12

jode


2 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));
like image 137
Saadi Avatar answered Jan 12 '23 01:01

Saadi


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));
like image 30
Kirk Larkin Avatar answered Jan 11 '23 23:01

Kirk Larkin