Tbooty Tbooty - 1 year ago 78
C# Question

Compare Elements in two lists and return a separate list of the original list that is different

I have a class that has the following fields.

class StandardizedModel
public string Case{ get; set; }
public DateTime? CreatedDateLocal { get; set; }
public DateTime? ClosedDateLocal { get; set; }
private string _status;

Let's say I make two lists with this custom class.

List1 ( main list)


What I am trying to do is compare the elements in the two lists, if they are different I need to return the original StandardizedModel from list1.

The two lists will always be the same size and the case will always exist in both lists, the dates and status can be different though.

I've tried using a linq's zip to try and compare the elements and then add them to a list but that returns 0.

List<StandardizedModel> testList = new List<StandardizedModel>();

var test = List1.Zip(List2, (a, b) =>
if (a =! b) { testList.Add(a);}
return testList;

Answer Source

You can use Enumerable.Join which is efficient:

var changes = from m1 in list1
              join m2 in list2 on m1.Case equals m2.Case
              where  m1.CreatedDateLocal != m2.CreatedDateLocal
                ||   m1.ClosedDateLocal  != m2.ClosedDateLocal
                ||   m1._status != m2._status
              select m1;
List<StandardizedModel> changeList = changes.ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download