List<string> list1 = new List<string>() { "0", "1" };
List<string> list2 = new List<string>() { "1", "0" };
如何比较上面两个集合list1、list2,它们是否相等
给出的条件是:只要其元素的个数、内容相等,就算相等,而不管元素的排序、索引值是否相等。
比如 { "0", "1" }与{ "1", "0" }算是相等的,{ "4", "5" }与{ "5", "4" } 也是相等的如何比较?

解决方案 »

  1.   

    http://topic.csdn.net/u/20120629/15/64a57b64-90a6-4206-9523-bc746193c1c1.html
      

  2.   


    public static bool isEqual(List<string> list1, List<string> list2)
            {
                list1.Sort();
                list2.Sort();
                if (list1.Count == list2.Count)
                {
                    int i = 0;
                    foreach (string str in list1)
                    {
                        if (str != list2[i])
                        {
                            return false;
                        }
                        i++;
                    }
                    return true;
                }            return false;
            }
      

  3.   


    if (list1.Count == list2.Count && list1.Except(list2).Count() == 0 && list2.Except(list1).Count() == 0)
    {
      //集合相等
    }
    //或者
    if (list1.Count == list2.Count && list1.All(x => list2.Contains(x)) && list2.All(x => list1.Contains(x)))
    {
      //集合相等
    }
      

  4.   

    方法真的很多,比如
    list1.Count == list2.Count && list1.OrderBy(x => x).Zip(list2.OrderBy(x => x), (x, y) => x == y).All(x => x == true);
      

  5.   


        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> listA = new List<string>() { "0", "1" };
            List<string> listB = new List<string>() { "1", "0" };
            int count = listA.Except(listB).ToList().Count;//这一句就够了
            if (count == 0)
            {
                Response.Write("相等"); return;
            }
            Response.Write("不相等");
        }//如果结合的结构相同,直接去他们差集或者交集就可以很好的得到答案了
      

  6.   

    如果集合有重复,单取一个差集不能判断。
    比如List<int> list1 = new List<int>() { 1, 1, 2, 3, 4 };
    List<int> list2 = new List<int>() { 1, 2, 3, 4, 5 };
    int count = list1.Except(list2).Count(); //count为0
      

  7.   

    先判断元素个数相不相等?不相等则直接return false,若相等,则继续判断,先排序(最好是自己规定比较格式),然后就好比较了
      

  8.   

    为什么不先判断是不是为null呢
      

  9.   


    谢谢。取差集确实欠考虑了。还是排序比较稳妥。
    list1.Count == list2.Count && list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x))
      

  10.   

    不用排序, 先判断长度,相等则遍历其中一个集合,元素在另一个集合中没有则直接返回false有则在另外的集合中移除该元素 并继续遍历。  复杂度比O(n)略高
      

  11.   

    不排序的话,比O(n)略高? 呵呵,高多少?
    复杂度明显是最好N ,最坏N^2 . 
    当然复杂度按最坏考虑是N^2
      

  12.   

    用哈希表进行内容比对就行,算法复杂度就是O(m+n)应该很快了。
    如果排序的话就太悲剧了没有必要排序
      

  13.   

    先比对大小。如果相等就用哈希表或者位图进行标记。
    算法复杂度基本上就是O(M+N)
      

  14.   

    对比哈希值。
    hash(set) = sum(hash(e) for e in set)