I want to compare the values of two lists for a program I'm making. I want it to compare the 1st value of List 1 to the first value of List 2, and then the second value of List 1 to the second value of List 2, and so on.
How would I go about doing this in C#?
Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not. Syntax: public virtual bool Equals (object obj);
Using list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
There is a special method for this, called SequenceEqual
:
IList<int> myList1 = new List<int>(...);
IList<int> myList2 = new List<int>(...);
if (myList1.SequenceEqual(list2)) {
...
}
You can do custom comparison of sequences using the Zip
method. For example, to see if any pair is not within the difference of three, you can do this:
IList<int> myList1 = new List<int>(...);
IList<int> myList2 = new List<int>(...);
if (myList1.Zip(list2, (a, b) => Math.Abs(a - b)).Any(diff => diff > 3)) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With