Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

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.

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"

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top