【问题标题】:Loop through two collections to compare for identical collections in C#循环遍历两个集合以比较 C# 中的相同集合
【发布时间】:2016-11-16 20:47:33
【问题描述】:

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

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

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

TIA。

【问题讨论】:

标签: c# collections foreach compare


【解决方案1】:

您可以使用用于此目的的.SequenceEqual 方法。阅读More

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

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

SequenceEqual(IEnumerable, IEnumerable) 方法并行枚举两个源序列并比较 使用默认相等比较器对应的元素 TSource,默认值。默认相等比较器 Default 用于 比较实现 IEqualityComparer 的类型的值 通用接口。要比较自定义数据类型,您需要 实现这个接口并提供你自己的 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
*/

【讨论】:

  • 为什么不return Code == other.Code &amp;&amp; Name == other.Name;?你知道CodeName 的类型(intstring)是与== 配合良好的密封类型。如果Namenull(您选择在GetHashCode 中处理的情况),您使用Name.Eqauls 的解决方案将会爆炸。
  • @JeppeStigNielsen 如前所述,此示例直接取自 MSDN。
  • 这并不妨碍我批评它。
  • @JeppeStigNielsen 绝对是。我只是指出这不是我的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2018-06-16
  • 2016-07-16
  • 2014-08-13
相关资源
最近更新 更多