日期:2014-05-18  浏览次数:20993 次

请问,如何比较这两个集合是否相等
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" } 也是相等的

如何比较?

------解决方案--------------------
最简单的:先看数量,数量相等再把它们排序,依次比较。
------解决方案--------------------
http://topic.csdn.net/u/20120629/15/64a57b64-90a6-4206-9523-bc746193c1c1.html
------解决方案--------------------
C# code

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

------解决方案--------------------
C# code

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)))
{
  //集合相等
}

------解决方案--------------------
方法真的很多,比如
list1.Count == list2.Count && list1.OrderBy(x => x).Zip(list2.OrderBy(x => x), (x, y) => x == y).All(x => x == true);
------解决方案--------------------
需要先排序,否则如果集合中有重复的元素很多方法就不灵了。三楼稳妥,五楼也对。
------解决方案--------------------
C# code

    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("不相等");
    }

------解决方案--------------------
探讨

C# code

protected void Page_Load(object sender, EventArgs e)
{
List<string> listA = new List<string>() { "0", "1" };
List<string> listB = new List<string>() { "1", "0" };
……

------解决方案--------------------
先看数量,数量相等再把它们排序,依次比较。
------解决方案--------------------
探讨
引用:

C# code

protected void Page_Load(object sender, EventArgs e)
{
List<string> listA = new List<string>() { "0", "1" };
List<string> listB = new List<string>() { "1", "0" };
……

如……

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