I have a situation where I have a list of ids such as {1,2开发者_JS百科,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.
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.
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.
精彩评论