簡體   English   中英

循環瀏覽兩個集合以比較C#中的相同集合

[英]Loop through two collections to compare for identical collections in C#

我有兩個集合,我想遍歷每個元素並比較每個集合中的對應元素是否相等,從而確定這些集合是否相同。

是否可以通過foreach循環實現?還是必須使用計數器並通過索引訪問元素?

一般來說,是否存在一種比較集合是否相等的首選方法,例如重載運算符?

TIA。

您可以使用用於此目的的.SequenceEqual方法。 閱讀更多

如果鏈接由於某種原因被關閉或刪除,請參見以下示例。

通過使用元素的默認相等比較器比較元素,確定兩個序列是否相等。

SequenceEqual(IEnumerable,IEnumerable)方法並行枚舉兩個源序列,並使用TSource的默認相等比較器Default來比較相應的元素。 默認的相等比較器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
*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM