Title: Determine whether two lists contain the same sequence of objects in C#
The IEnumerable interface provides a SequenceEqual method that determines whether two IEnumerable sequences contain the same objects. Normally, it uses reference equality so it considers two objects equal only if they refer to the same instance. However, if the objects implement IEquatable, then SequenceEqual tests object equality.
This example uses the following Person class.
public class Person : IEquatable<Person>
{
public string FirstName, LastName;
public Person(string first_name, string last_name)
{
FirstName = first_name;
LastName = last_name;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
// IEquatable<Person>
public bool Equals(Person other)
{
// If other is null, we're not equal.
if (Object.ReferenceEquals(other, null)) return false;
// If the references are the same, we are equal.
if (Object.ReferenceEquals(this, other)) return true;
// We're equal if the names are equal.
return FirstName.Equals(other.FirstName) &&
LastName.Equals(other.LastName);
}
}
The main program makes three lists of Person objects. All three contain different Person instances that happen to have the same names. The third list, however, contains two of the objects in a different order. Look at the picture to see what objects each list contains.
The program then uses the following code to see which lists are equal.
lblAEqualsB.Text = "A == B: " + list_a.SequenceEqual(list_b);
lblAEqualsC.Text = "A == C: " + list_a.SequenceEqual(list_c);
You can see from the picture that SequenceEqual considers lists A and B equal, but it considers lists A and C unequal because they contain the same objects in different orders.
This makes SequenceEqual useful only in the rather limited case where you want to know if two lists contain the same items in the same order. In my next post, I'll describe two ways you can determine whether two sequences are the same but in different orders.
Download the example to experiment with it and to see additional details.
|