Tsukasa
Tsukasa

Reputation: 6552

Compare Two List<Objects>

What is the best route to compare 2 List<MyClasses>?

List 2 could contain more values than List 1 which is ok. Just need to make sure List 2 contains everything in List 1. They also won't be in the same order.

Upvotes: 0

Views: 98

Answers (4)

Aaron Palmer
Aaron Palmer

Reputation: 8982

This will let you know if list2 does not contain an item that is in list1:

list1.Any(x => !list2.Contains(x));

You could put it in a variable so you don't have to think about the double negatives:

var list2ContainsList1 = !list1.Any(x => !list2.Contains(x));

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61339

One way to do it:

List1.All(o => List2.Contains(o));

This says "return true if and only if every item in list 1 is contained in list 2"

Upvotes: 1

Alberto Solano
Alberto Solano

Reputation: 8227

The simplest approach is to use Except (in your case, you don't care about the order of your elements in the lists):

var elementsInList2NotInList1 = list2.Except(list1);

Remember that this method uses a default equality comparer to compare the values. If you do care about the ordering of the elements, you'll need to do extra work, in order to check how each element of a list is equal to an element of the other list. The extra work would be the following:

  1. Create your own comparer, implementing the interface IEqualityComparer;
  2. Create your own Equals() and GetHashCode() methods for your custom data type.

Upvotes: 1

Servy
Servy

Reputation: 203802

You can use Except to find the set difference of two collections.

var hasAllItems = !list2.Except(list1).Any();

Upvotes: 6

Related Questions