7

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

ShaunRussell
  • 85
  • 3
  • 7

1 Answers1

12

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)) {
    ...
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523