C# - How to compare a list of strings, ints or longs with another list

You can check if two lists have the same content and in the same sequence using SequenceEqual:

var list1 = new List<int> { 1, 2, 3, 4, 5 };
var list2 = new List<int> { 1, 2, 3, 4, 5 };

var areEqual = list1.SequenceEqual(list2);
//areEqual is true

This will fail if the sequence is different, but the contents are the same:

var list1 = new List<int> { 5, 4, 3, 2, 1 };
var list2 = new List<int> { 1, 2, 3, 4, 5 };

var areEqual = list1.SequenceEqual(list2);
//areEqual is false

If you want to check whether the items of one list is within another you can use Except in combination with Any:

var list1 = new List<int> { 5, 4, 3, 2, 1};
var list2 = new List<int> { 1, 2, 3, 4, 5 };

var areEqual = !list1.Except(list2).Any();
//areEqual is true

However this has some drawbacks as there might be duplicates in the lists. If performance is less of a concern the two lists can be ordered before using a SequenceEqual call:

var list1 = new List<int> { 5, 4, 3, 2, 1 };
var list2 = new List<int> { 1, 2, 3, 4, 5 };

var areEqual = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));
//areEqual is true

In the above we combine OrderBy with SequenceEqual to sort the lists before comparing them.

The above examples are using ints, but they could also have been done with longs or strings.

That is all

I hope you found the above useful or as inspiration for the comparison you need to do. Let me know if you have any comments down below!

References: