1

I want to compare two lists, item by item. How can I express the following code using linq?

bool result = true;
var list1 = new List<int> { 10, 20, 30, 40 };
var list2 = new List<int> { 10, 20, 30, 40 };
for (int index = 0; index < list1.Count(); index++)
{
   result &= list1[index] == list2[index];
}
sloth
  • 99,095
  • 21
  • 171
  • 219
Lasse Normann
  • 579
  • 6
  • 11

1 Answers1

8

You can use SequenceEqual:

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

Example:

bool result = list1.SequenceEqual(list2);
sloth
  • 99,095
  • 21
  • 171
  • 219
  • 3
    Linq is so powerful. Sometime it will conquer the world. Btw I would consider to check count of items in lists before enumerating them. Something like `result = (list1.Count == list2.Count) && list1.SequenceEqual(list2)` – Sergey Berezovskiy May 22 '14 at 14:38
  • @SergeyBerezovskiy Why doesn't the Linq implementation doesn't do this itself? – CodingIntrigue May 22 '14 at 14:47
  • 3
    @RGraham nope, it does not - it simply gets enumerators from both enumerables and iterates while both have items and those items are equal. There is nothing specific to argument type (array, ICollection etc). [Proof](http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs) – Sergey Berezovskiy May 22 '14 at 14:51