I have a situation where I have a list of ids such as {1,2,3,4}. I need to pass into a method another list of ids and if the list has the same numbers in it return true, else if either list is not identical (disregarding ordering) I need to return false. So, a call to the method with {1,2,3,4,5} should return false while a call with {2,4,1,3} returns true. This sounds simple enough but I can't figure out how to do it.
+2
A:
The simplest way is probably this:
var idSet = new HashSet<int>(idList1);
if (idSet.SetEquals(idList2))
{
...
}
As per the comments, this will consider {1, 1, 1, 1, 1} to be equal to {1} - in other words, it treats it as a set instead of an unordered collection of possibly-duplicate values.
Jon Skeet
2010-10-07 20:33:46
A reminder that LINQ is not a silver-bullet to working with collections.
Programming Hero
2010-10-07 20:42:53
I'd add a caveat that this will not work if the list has repeating elements. It's stated that they're IDs in the question, and so might assume that they don't repeat. But such is not stated explicitly.
jdmichal
2010-10-07 20:48:23
@jdmichal: True. Will update to mention this.
Jon Skeet
2010-10-07 20:51:50
A:
If you are guaranteed to not have repeating elements in idList
, you can use the following:
if (idList.Count == otherIDList.Count &&
idList.Intersect(otherIDList).Count() == idList.Count)
{
// Contain same things.
}
else
{
// Do not contain same things.
}
The first check is to make sure they're the same size. This is a really cheap way to see if the lists even have a chance of being identical, same as with strings. Also, without it, the statement will return true if otherIDList
is a superset of idList
.
If you cannot guarantee uniqueness within the collection, I think you're going to have to code something yourself.
jdmichal
2010-10-07 20:46:57
Thanks. I was thinking of the intersect method but I couldn't remember what it was called. Thanks again!
geoff swartz
2010-10-08 12:23:00