tags:

views:

102

answers:

4

This should be easy.

I want to check whether two list are the same in that they contain all the same elements or not, orders not important.

Duplicated elements are considered equal, i.e.e, new[]{1,2,2} is the same with new[]{2,1}

A: 

You need to get the intersection of the two lists:

bool areIntersected = t1.Intersect(t2).Count() > 0;

In response to you're modified question:

bool areSameIntersection = t1.Except(t2).Count() == 0 && t2.Except(t1).Count() == 0;
jrista
I think my question is not phrased clearly... I've modified the question
Ngu Soon Hui
If `t1` is { 1, 2, 2 } and `t2` is { 1, 2, 2 }, this will incorrectly return false.
280Z28
A: 

If the count of list1 elements in list2 equals the count of list2 elements in list1, then the lists both contain the same number of elements, are both subsets of each other - in other words, they both contain the same elements.

if (list1.Count(l => list2.Contains(l)) == list2.Count(l => list1.Contains(l)))
    return true;
else
    return false;
Kirk Broadhurst
+4  A: 

Edit: This was written before the OP added that { 1, 2, 2 } equals { 1, 1, 2 } (regarding handling of duplicate entries).

This will work as long as the elements are comparable for order.

bool equal = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));
280Z28
This wont help with duplicates.
leppie
@leppie: What do you mean? If `list1` contains 4 `3`, then `equal` would only be true if `list2` also contained exactly 4 `3`. Duplicates work fine.
280Z28
You can take out the OrderBy calls if the order of the sequence will be the same; such as when you are comparing occurrence lists from tests.
Jason
@Jason: True, but the question explicitly states that you can't assume anything about the order of the elements.
280Z28
And what about 3 elements vs 10 elements, all elements being 'a'.
leppie
@leppie: Then obviously the lists are not the same, and it returns the correct answer: false.
280Z28
But they contain all the same elements, like the OP asked.
leppie
+3  A: 
var same = list1.Except(list2).Count() == 0 && 
           list2.Except(list1).Count() == 0;
leppie
well there, I forgot the second bit, no need to downvote...
leppie
What is a differing duplicate?
leppie