开发者

LINQ: check whether two list are the same

This should be easy.

I want to check whether two list are the same in tha开发者_开发知识库t 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}


var same = list1.Except(list2).Count() == 0 && 
           list2.Except(list1).Count() == 0;


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));


The SetEquals of HashSet is best suited for checking whether two sets are equal as defined in this question

        string stringA = "1,2,2";
        string stringB = "2,1";

        HashSet<string> setA = new HashSet<string>((stringA.Trim()).Split(',').Select(t => t.Trim()));
        HashSet<string> setB = new HashSet<string>((stringB.Trim()).Split(',').Select(t => t.Trim()));

        bool isSetsEqual = setA.SetEquals(setB);

REFERENCE:

  1. Check whether two comma separated strings are equal (for Content set)


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;


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜