Compare Lists and Get Values ​​with Linq

advertisements

My object is "MyClass" with 2 properties : Id (int) and HourBy (int)

I have two list :

var List1 = new List<MyClass>();
var List2 = new List<MyClass>();

I'd like to get one list with : - Object from List1 present in List2 based on Id with Hourby (list2) < Hourby in List1 - Object from List1 no present in List2

//#Sample1
//List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
//I'd like to get :
new MyClass(2,5);
new MyClass(3,30);

//Sample2
List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
List2.add(new MyClass(2,2));
//I'd like to get :
new MyClass(2,3);
new MyClass(3,30);

Thanks,


You can do this by the following Linq statement:

var result = List1.Where(x => !List2.Select(y => y.Id).Contains(x.Id)
    || List2.Single(y => x.Id == y.Id).HourBy < x.HourBy);

Best Regards