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

8
  • 1
    See stackoverflow.com/questions/1546925/… Commented Dec 14, 2011 at 16:31
  • Is sequence item position shoudl be considered? Commented Dec 14, 2011 at 16:32
  • @Ozkan what if you had duplicates? like numbers: { 1, 1, 2} and numbers2: { 1, 2 } would you consider those equal? Commented Dec 14, 2011 at 16:34
  • @Matthew Cox, Hi, this is not considered to occur. But I found the method its SequenceEqual() Commented Dec 14, 2011 at 16:36
  • 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 Commented Dec 14, 2011 at 16:40

2 Answers 2

4

Use Enumerable.SequenceEqual, but Sort the lists first.

Sign up to request clarification or add additional context in comments.

Comments

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;

1 Comment

That would be my answer. Just depends on if duplicates matter. If they do then this would return a false positive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.