2

I have two collections and I want to loop through each element and compare the corresponding elements in each collection for equality, thus determining if the collections are identical.

Is this possible with a foreach loop or must I use a counter and access the elements by index?

Generally speaking is there a preferred method for comparing collections for equality, like overloading an operator?

TIA.

  • Possible duplicate of [Is there a built-in method to compare collections in C#?](http://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c) – Ivan Jul 14 '16 at 05:13

1 Answers1

4

You can use .SequenceEqual method which is used for this purpose. Read More.

Examples below if link is down or removed for some reason.

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

The SequenceEqual(IEnumerable, IEnumerable) method enumerates the two source sequences in parallel and compares corresponding elements by using the default equality comparer for TSource, Default. The default equality comparer, Default, is used to compare values of the types that implement the IEqualityComparer generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.

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

If you want to compare the actual data of the objects in the sequences instead of just comparing their references, you have to implement the IEqualityComparer generic interface in your class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.

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;
    }
}

Usage:

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
*/
Zein Makki
  • 29,485
  • 6
  • 52
  • 63