Link to home
Start Free TrialLog in
Avatar of jackjohnson44
jackjohnson44

asked on

C# determine if list of strings have same value without regard to position

I have two list of strings I am getting from a function.  How can I tell if they are identical without respect to the order.

meaning

list1 = {"a", "b", "c"}
list2 = {"c", "b", "a"}
list3 = {"a")

list1 and list2 would be equal
list1 and list3 would not be equal
list2 and list3 would not be equal
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you cannot use LINQ (for whatever reason), then the "old school" approach would be to sort the lists and then compare  each element:

bool areEqual = true;

list1.Sort();
list2.Sort();

if (list1.Length != list2.Length)
{
    areEqual = false;
}
else
{
    for (int i = 0; i < list1.Length; i++)
    {
        if (list1[i] != list2[i])
        {
            areEqual = false;
        }
    }
}

Open in new window

Normally I would say that Enumerable.SequenceEqual would suffice, but in this case (since the items are out of order) it would not.  So you would sort the items before comparing:
Enumerable.SequenceEqual(list1.OrderBy(i => i), list2.OrderBy(i => i))

Open in new window


For custom types, you will have to implement a comparer if the standard comparer does not work.  In those cases, code would be changed to:
Enumerable.SequenceEqual(list1.OrderBy(i => i, myListComparer), list2.OrderBy(i => i, myListComparer))

Open in new window


More information on implementing a comparer:

http://msdn.microsoft.com/en-us/library/234b841s(v=vs.110).aspx

-saige-