C# 对比两个List是否相等

本文通过两个示例详细解释了如何使用SequenceEqual方法判断两个序列是否相等。第一个示例展示了当序列包含对相同对象的引用时,SequenceEqual返回true;而第二个示例则表明,即使序列数据相同,但因对象引用不同,SequenceEqual会返回false。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**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.
*/

本文摘自官方案例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值