这个问题已经在这里有了答案:




9年前关闭。






我写

更新-更正:

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

有没有更短的方法?
我知道有SequenceEqual,但是顺序对我来说并不重要。

最佳答案

即使顺序对您而言并不重要,也并不排除SequenceEqual是可行的选择。

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

10-05 23:51