Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to compare if two IEnumerable<T> have the same items in C#? [duplicate]

Possible Duplicate:
Test whether two IEnumerable<T> have the same values with the same frequencies

I wrote

UPDATED - correction:

static bool HaveSameItems<T>(this IEnumerable<T> self, IEnumerable<T> other)
{
    return ! 
    ( 
        other.Except(this).Any() ||
        this.Except(other).Any()
    );
}

Isn't there a shorter way? I know there is SequenceEqual but the order doesn't matter for me.

like image 231
Jader Dias Avatar asked Feb 03 '11 13:02

Jader Dias


1 Answers

Even if the order doesn't matter to you, it doesn't rule out SequenceEqual as a viable option.

var lst1 = new [] { 2,2,2,2 };
var lst2 = new [] { 2,3,4,5 };
var lst3 = new [] { 5,4,3,2 };

//your current function which will return true
//when you compare lst1 and lst2, even though
//lst1 is just a subset of lst2 and is not actually equal
//as mentioned by Wim Coenen
(lst1.Count() == lst2.Count() &&
        !lst1.Except(lst2).Any()); //incorrectly returns true

//this also only checks to see if one list is a subset of another
//also mentioned by Wim Coenen
lst1.Intersect(lst2).Any(); //incorrectly returns true

//So even if order doesn't matter, you can make it matter just for
//the equality check like so:
lst1.OrderBy(x => x).SequenceEqual(lst2.OrderBy(x => x)); //correctly returns false
lst3.OrderBy(x => x).SequenceEqual(lst2.OrderBy(x => x)); // correctly returns true
like image 72
diceguyd30 Avatar answered Oct 26 '22 23:10

diceguyd30