The following code examples demonstrate how to use SequenceEqual
(IEnumerable, IEnumerable) to determine whether two sequences are equal. In the first two examples, the method determines whether the compared sequences contain references to the same objects. In the third and fourth examples, the method compares the actual data of the objects within the sequences.
In this example the sequences are equal.
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);
outputBlock.Text += String.Format(
"The lists {0} equal.",
equal ? "are" : "are not") + "\n";
}
/*
This code produces the following output:
The lists are equal.
*/
The following code example compares two sequences that are not equal. Note that the sequences contain identical data, but because the objects that they contain have different references, the sequences are not considered equal.
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;
}
}
After you implement this interface, you can use sequences of Product objects in the SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method, as shown in the following example.
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);
outputBlock.Text += "Equal? " + equalAB + "\n";
/*
This code produces the following output:
Equal? True
*/
No comments:
Post a Comment