Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Values of 2 Lists C# [duplicate]

Tags:

c#

list

compare

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#?

like image 825
ShaunRussell Avatar asked Jun 15 '13 02:06

ShaunRussell


People also ask

Can we compare two lists 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);

Can you compare lists with == in Python?

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.


1 Answers

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)) {
    ...
}
like image 65
Sergey Kalinichenko Avatar answered Sep 21 '22 18:09

Sergey Kalinichenko