3

What is the best way to compare two lists based on values, order and the number of values. So all of the lists below should be different.

var list1 = new List<string> { "1", "2" };
var list2 = new List<string> { "2", "1" };
var list3 = new List<string> { "1", "2", "3" };
Vahid
  • 5,144
  • 13
  • 70
  • 146
  • Compare usually means to determine order. You just want to determine equality right? – weston May 03 '14 at 09:12
  • I guess I do. I want to check the equality of the lists based on those criteria. – Vahid May 03 '14 at 09:14
  • possible duplicate of [How to compare two List using LINQ in C#](http://stackoverflow.com/questions/3319787/how-to-compare-two-liststring-using-linq-in-c-sharp) – Matthijs Wessels May 03 '14 at 10:01

2 Answers2

5

How about using SequenceEqual.

See http://ideone.com/yZeYRh

var a = new [] { "1", "2", "3" };
var b = new [] { "1", "2" };
var c = new [] { "2", "1" };

Console.WriteLine(a.SequenceEqual(b)); // false
Console.WriteLine(a.SequenceEqual(c)); // false
Console.WriteLine(c.SequenceEqual(b)); // false

It comes from the namespace System.Linq and can be used on any IEnumerable.

You can also pass it an IEqualityComparer to for example also do:

var d = new [] { "a", "B" };
var e = new [] { "A", "b" };

Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
Matthijs Wessels
  • 6,530
  • 8
  • 60
  • 103
1

I like Zip for this, but you still need to manually compare Count.

lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);
weston
  • 54,145
  • 21
  • 145
  • 203