循环遍历两个集合以比较 C# 中的相同集合

本文关键字:集合 比较 循环 两个 遍历 | 更新日期: 2023-09-27 17:56:56

>我有两个集合,我想遍历每个元素并比较每个集合中的相应元素是否相等,从而确定集合是否相同。

这是否可以通过 foreach 循环实现,或者我必须使用计数器并按索引访问元素?

一般来说,是否有比较集合相等性的首选方法,例如重载运算符?

蒂亚。

循环遍历两个集合以比较 C# 中的相同集合

您可以使用

用于此目的.SequenceEqual方法。阅读更多。

以下示例,如果链接由于某种原因关闭或删除。

通过比较元素来确定两个序列是否相等 通过对其类型使用默认相等比较器。

序列相等(IEnumerable, IEnumerable) 方法并行枚举两个源序列并进行比较 使用默认相等比较器的相应元素 默认,默认。默认相等比较器"默认"用于 比较实现 IE质量比较器的类型的值 通用接口。要比较自定义数据类型,您需要 实现此接口并提供您自己的 GetHashCode 和 Equals 类型的方法。

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

如果要比较序列中对象的实际数据 您不仅要比较它们的引用,还必须实现 类中的 IEqualityComparer 通用接口。以下 代码示例演示如何在自定义数据中实现此接口 键入并提供 GetHashCode 和 Equals 方法。

public class Product : IEquatable<Product>
{
    public string Name { get; set; }
    public int Code { get; set; }
    public bool Equals(Product other)
    {
        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;
        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;
        //Check whether the products' properties are equal.
        return Code.Equals(other.Code) && Name.Equals(other.Name);
    }
    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.
    public override int GetHashCode()
    {
        //Get hash code for the Name field if it is not null.
        int hashProductName = Name == null ? 0 : Name.GetHashCode();
        //Get hash code for the Code field.
        int hashProductCode = Code.GetHashCode();
        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}

用法:

Product[] storeA = { new Product { Name = "apple", Code = 9 },
                            new Product { Name = "orange", Code = 4 } };
Product[] storeB = { new Product { Name = "apple", Code = 9 },
                            new Product { Name = "orange", Code = 4 } };
bool equalAB = storeA.SequenceEqual(storeB);
Console.WriteLine("Equal? " + equalAB);
/*
    This code produces the following output:
    Equal? True
*/