How to compare two objects in c# using linq

How to Compare Two Objects in C# using LINQ

In C#, comparing two objects can be done using the Enumerable.SequenceEqual method from the LINQ library. This method allows you to check whether two sequences contain the same elements in the same order. Here is an example demonstrating how to compare two objects in C# using LINQ:


using System;
using System.Linq;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void Main()
{
    // Create two Person objects
    var person1 = new Person { Name = "John", Age = 25 };
    var person2 = new Person { Name = "John", Age = 25 };

    // Compare the two objects using LINQ
    var objectsAreEqual = Enumerable.SequenceEqual(person1.GetType().GetProperties().Select(p => p.GetValue(person1)), 
                                                  person2.GetType().GetProperties().Select(p => p.GetValue(person2)));

    if (objectsAreEqual)
    {
        Console.WriteLine("The objects are equal.");
    }
    else
    {
        Console.WriteLine("The objects are not equal.");
    }
}
  

In this example, we have a class called “Person” with two properties: “Name” and “Age”. We create two instances of this class, “person1” and “person2”, with the same values for their properties.

To compare the two objects, we use LINQ’s Enumerable.SequenceEqual method. We pass two sequences of property values for “person1” and “person2” using reflection. The GetValue method retrieves the current value of each property, and Select projects these values into a sequence.

The Enumerable.SequenceEqual method then compares the two sequences element by element, checking whether they contain the same values in the same order. If all the elements are equal, it returns true, indicating that the objects are equal. Otherwise, it returns false.

In the example, since the properties of “person1” and “person2” have the same values, the output will be “The objects are equal.”

Note that this method only compares the values of public properties in the objects. If your objects have nested objects or collections, you would need to recursively compare those as well.

Leave a comment