1

I am stucked in a situation where I am having two lists. What will be the correct way to compare the two and get the result in third list. But here is a small catch. See example below:

ListOld = { [Name=Amit, Class=V, Roll=3], [Name=Naveen, Class=V, Roll=3], [Name=Sammy, Class=V, Roll=3], [Name=Neil, Class=X, Roll=21], [Name=John, Class=VI, Roll=63]}; ListNew = { [Name=Amit, Class=VI, Roll=13], [Name=Naveen, Class=VII, Roll=3], [Name=Sammy, Class=V, Roll=3], [Name=Sanjay, Class=VIII, Roll=2]}; ResultantList = { [Name=Amit, Class=VI, Roll=13], [Name=Naveen, Class=VII, Roll=3], [Name=Sanjay, Class=VIII, Roll=2]}; 

In above example, ListNew has got 3 changes, that are updates in Amit and Naveen , and Sanjay as a new member.

So In my query I need to compare both the list and want to pick either updated or added item in first list.

I tried, Except(), Intersect(), union(), with Equality Interfaces but no success. Kindly help.

1 Answer 1

2

You can do it by writing an IEqualityComparer

public class SomeClassComparer : IEqualityComparer<SomeClass> { public bool Equals(SomeClass x, SomeClass y) { return x.Name == y.Name && x.Class == y.Class && x.Roll == y.Roll; } public int GetHashCode(SomeClass obj) { return (obj.Name + obj.Class).GetHashCode(); } } 

Now, the linq is simple

var result = ListNew.Except(ListOld , new SomeClassComparer()).ToList(); 

You can also do the same thing by overiding ToString and GetHashcode methods, but IEqualityComparer is good especially when you have no control over the class you use.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but the same I tried and it didn't worked. AFAIK Equality Comparing interfaces work only when we have similaritirs. But here inmy case. I need to figure out the diference and pick those one
@AmitRanjan I also tested it and it works. How about posting a small, compilable test case showing what you have tried So that we can talk about the same code..