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

Suppose I have two lists:

foo1<T>
foo2<T>

each list has the property Idthat int, I need to check if all the identifiers of the list are equal to the foo1list foo2, what I did:

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

so if all values ​​of Idseach element are equal, should be returned falseif almost one another should return true. Both lists are already ordered.

In fact, I get even true, but it should return false, because all my elements Idsare equal.

What am I doing wrong?

Thank.

+4
source share
4 answers

You can use the extension methods All and Any Linq.

, :

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

SequenceEqual :

, , , .

:

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

The easiest 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);
+1
source

You need to include the index also when you compare every two elements

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

Source: https://habr.com/ru/post/1688929/


All Articles