[LINQ Operators] SequenceEqual

The “SequenceEqual” operator checks whether two sequences are equal. It returns a boolean value (true/false) and you can provide the custom comparer “IEqualityComparer<T>”.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “SequenceEqual” operator

  • NonDeferred operator
  • Purpose: Conversion

 

3. Prototypes

public static bool SequenceEqual<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second)

public static bool SequenceEqual<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second,
  IEqualityComparer<T> comparer)

The “SequenceEqual()” operator determines whether two sequences are equal by comparing the elements. it returns true if the two source sequences are of equal length and their corresponding elements are equal.

 

4. Example 1 (Standard Operator)

var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNumbers = new List<int> { 1, 3, 5, 7, 9 };

bool isEqual =
  numbers.Where(i => i%2 == 1).SequenceEqual(oddNumbers);

Console.WriteLine($"Are two sequences equal : {isEqual}"); // True

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “SequenceEqual()” operator.

 

6. Example 3 (Standard Operator) – with a custom comparer

public class EmpNameComparer : IEqualityComparer<Employee>
{
  public bool Equals(Employee x, Employee y)
  {
    return x.Name.Equals(y.Name);
  }
  public int GetHashCode(Employee obj)
  {
    return obj.Name.GetHashCode();
  }
}

 

var empsTake2 = Employee.GetEmployees().Take(2);
var empsCreate2 = new List<Employee>
  {
    new Employee { ID=1, Name="Tom Harris", CityID= 1 },
    new Employee { ID=2, Name="Jane Smith", CityID= 2 }
  };

EmpNameComparer comp = new EmpNameComparer();

bool isEqual =
  empsTake2.SequenceEqual(empsCreate2, comp);

Console.WriteLine($"Are two sequences equal : {isEqual}"); // True

Feel free to change the names to make the result false.

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