Ozkan
Ozkan

Reputation: 2041

compare two identical lists of strings

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

Upvotes: 1

Views: 1198

Answers (2)

kol
kol

Reputation: 28698

Use Enumerable.SequenceEqual, but Sort the lists first.

Upvotes: 4

sll
sll

Reputation: 62504

// 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;

Upvotes: 2

Related Questions