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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
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:
More information on implementing a comparer:
http://msdn.microsoft.com/en-us/library/234b841s(v=vs.110).aspx
-saige-
Enumerable.SequenceEqual(list1.OrderBy(i => i), list2.OrderBy(i => i))
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))
More information on implementing a comparer:
http://msdn.microsoft.com/en-us/library/234b841s(v=vs.110).aspx
-saige-
Open in new window