1

Let's say I have following code:

    List<string> numbers = new List<string> { "1", "2" };
    List<string> numbers2 = new List<string> { "1", "2"};

    if (numbers.Equals(numbers2))
    {

    }

Like you can see I have two lists with identical items. Is there a way to check if these two lists are equal by using one method?

SOLUTION:

Use SequenceEqual()

Thanks

Ozkan
  • 2,011
  • 6
  • 29
  • 43
  • 1
    See http://stackoverflow.com/questions/1546925/comparing-two-liststring-for-equality – dash Dec 14 '11 at 16:31
  • Is sequence item position shoudl be considered? – sll Dec 14 '11 at 16:32
  • @Ozkan what if you had duplicates? like `numbers: { 1, 1, 2}` and `numbers2: { 1, 2 }` would you consider those equal? – Matthew Cox Dec 14 '11 at 16:34
  • @Matthew Cox, Hi, this is not considered to occur. But I found the method its `SequenceEqual()` – Ozkan Dec 14 '11 at 16:36
  • Before calling SequenceEqual, you have to sort the lists. – kol Dec 14 '11 at 16:39
  • 2
    If all you want to do is "compare two identical lists of strings", then `return true` will do the job. It's also the fastest solution – jalf Dec 14 '11 at 16:40
  • Very good, that made me smile. – dash Dec 14 '11 at 16:41
  • possible duplicate of [Is there a built-in method to compare collections in C#?](http://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c) – nawfal Nov 08 '13 at 23:06

2 Answers2

4

Use Enumerable.SequenceEqual, but Sort the lists first.

kol
  • 27,881
  • 12
  • 83
  • 120
2
// if order does not matter
bool theSame = numbers.Except(numbers2).Count() == 0;

// if order is matter
var set = new HashSet<string>(numbers);
set.SymmetricExceptWith(numbers2);
bool theSame = set.Count == 0;
sll
  • 61,540
  • 22
  • 104
  • 156
  • 2
    That would be my answer. Just depends on if duplicates matter. If they do then this would return a false positive. – Matthew Cox Dec 14 '11 at 16:35