# Compare two objects and list down the changes using LINQ

Posted by in C# category on for Beginner level | Points: 250 | Views : 5123

Sometimes back while answering a DNF forum question , we came across an interesting situation where the person has asked a nice question as how to Compare two objects and then to list down the changes of the same.In this article we will address the problem and present a solution for it.

## Introduction

Sometimes back while answering a DNF forum question , we came across an interesting situation where the person has asked a nice question as how to Compare two objects and then to list down the changes of the same.In this article we will address the problem and present a solution for it.

## Environment Setup

So let us setup the environment first

```using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
{
};

{
};
}
}

{
public string Address { get; set; }
}

{
public string Address { get; set; }
}
}
```

We have two entities, OriginalAddress and PresentAddress. We have populated some data to those and the objective is to find out those addresses that have been changed.

## Approach to solve the problem

We have two sets viz. OriginalAddress and PresentAddress. First, we will find out those elements that has been changed in second set.Next we will find out those elements that has been changed in first set.

Once done, we will merge the two sets results to get the desired result

## Using the code

``` //Step 1: Values of First Set Changed In Second Set

//Step 2: Values of Second Set Changed In First Set

//Step 3: Merge the two sets results to get the desired result
valuesofFirstSetChangedInSecondSet
.Zip(valuesofSecondSetChangedInFirstSet, (o, p) =>
("Original Address : " + o + "   Present Address : " + p)
)
.ToList()
.ForEach(i => Console.WriteLine(i + Environment.NewLine)); //print the result
```

We are using the EXCEPT extension method of the static Enumerable class. It produces the set difference of two sequences by using the default equality comparer to compare values.Once done, we need to merge the two sets for which we are using the ZIP extension method that merges two sequences by using the specified predicate function.

Enumerable.Zip

## Conclusion

So in this article, we have seen as how we can compare two objects and list down the changes between them.Hope you enjoyed reading the article.Zipped file is attached herewith.

Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team

Login to vote for this post.