1. 程式人生 > >C# 對比兩個List是否相等

C# 對比兩個List是否相等

**SequenceEqual **

以下程式碼示例演示如何使用SequenceEqual (IEnumerable ,IEnumerable ) 來確定兩個序列是否相等。在前兩個示例中,該方法確定比較的序列是否包含對相同物件的引用。在第三和第四示例中,該方法比較序列內物件的實際資料。

在這個例子中,序列是相等的。

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void SequenceEqualEx1()
{
    Pet pet1 = new Pet { Name = "Turbo", Age = 2 };
    Pet pet2 = new Pet { Name = "Peanut", Age = 8 };

    // Create two lists of pets.
    List<Pet> pets1 = new List<Pet> { pet1, pet2 };
    List<Pet> pets2 = new List<Pet> { pet1, pet2 };

    bool equal = pets1.SequenceEqual(pets2);

    Console.WriteLine(
        "The lists {0} equal.",
        equal ? "are" : "are not");
}

/*
 This code produces the following output:

 The lists are equal.
*/

以下程式碼示例比較了兩個不相等的序列。請注意,序列包含相同的資料,但由於它們包含的物件具有不同的引用,因此序列不被視為相等。

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void SequenceEqualEx2()
{
    Pet pet1 = new Pet() { Name = "Turbo", Age = 2 };
    Pet pet2 = new Pet() { Name = "Peanut", Age = 8 };

    // Create two lists of pets.
    List<Pet> pets1 = new List<Pet> { pet1, pet2 };
    List<Pet> pets2 =
        new List<Pet> { new Pet { Name = "Turbo", Age = 2 }, 
                        new Pet { Name = "Peanut", Age = 8 } };

    bool equal = pets1.SequenceEqual(pets2);

    Console.WriteLine("The lists {0} equal.", equal ? "are" : "are not");
}

/*
 This code produces the following output:

 The lists are not equal.
*/

本文摘自官方案例。