# Jean Paul's Blog

## Lambda Expressions Extension Methods Series 11 -SequenceEqual()

Posted by Paul on November 13, 2011

In this small article, I would like to introduce the SequenceEqual() method. This method is very handy to compare two IEnumerable and return a Boolean stating whether each elements of both IEnumerable are same or not.

Method: SequenceEqual()

Arguments: IEnumerable<>

Operates On: IEnumerable

Returns: True/False

Example

Let us have two lists of integers.

List 1 having

1

2

3

List 2 having

1

2

3

Here both the list are of same elements. We can use the SequenceEquals() method to view the result:

bool result1 = list1.SequenceEqual(list2);

Output

The output of the above code will be:

True

Code Explained

Here on calling the SequenceEquals() method, each element of list1 is compared with corresponding element of list2. The default Equals() comparison is exercised here.

Elements of primitive types will have value comparison and

Elements of class types will have reference comparison (unless they override the Equals() method)

Sample Code with int and object Scenarios

// Creating list of int

IList<int> list1 = new List<int>() { 1, 2, 3 };

IList<int> list2 = new List<int>() { 1, 2, 3 };

IList<int> list3 = new List<int>() { 4, 5, 6 };

bool result1 = list1.SequenceEqual(list2); // True

bool result2 = list1.SequenceEqual(list3); // False

// Creating employee objects

Employee employee1 = new Employee() { Id = 1, Name = “Employee1” };

Employee employee2 = new Employee() { Id = 2, Name = “Employee2” };

IList<Employee> list4 = new List<Employee>();

IList<Employee> list5 = new List<Employee>();

bool result3 = list4.SequenceEqual(list5); // True – As Same ref of Employee objects

The Employee class would be having following structure:

public class Employee

{

public int Id;

public double Salary;

public int Age;

public string Name;

public override string ToString()

{

return this.Id.ToString() + ” ” + this.Name;

}

}