Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

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>();

list4.Add(employee1);

list4.Add(employee2);

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

list5.Add(employee1);

list5.Add(employee2);

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;

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s