Determine whether two lists contain the same sequences 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) &&

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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in lists, miscellany, OOP and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Determine whether two lists contain the same sequences of objects in C#

  1. Smithd902 says:

    Pretty great post. I just stumbled upon your blog and wished to say that I’ve really enjoyed surfing around your weblog posts. In any case I will be subscribing to your feed and I am hoping you write again soon!

  2. Pingback: Determine whether two lists contain the same sequences of objects in different orders in C# - C# HelperC# Helper

Comments are closed.