Compare two Lists for differences

前端 未结 5 998
逝去的感伤
逝去的感伤 2020-11-27 13:04

I would like some feedback on how we can best write a generic function that will enable two Lists to be compared. The Lists contain class objects and we would like to iterat

5条回答
  •  温柔的废话
    2020-11-27 13:18

    I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.

    If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.

    Here is how to do it in Linq:

    List listA = new List();
            List listB = new List();
    
            listA.Add(new Employee() { Id = 1, Name = "Bill" });
            listA.Add(new Employee() { Id = 2, Name = "Ted" });
    
            listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
            listB.Add(new Employee() { Id = 3, Name = "Jim" });
    
            var identicalQuery = from employeeA in listA
                                 join employeeB in listB on employeeA.Id equals employeeB.Id
                                 select new { EmployeeA = employeeA, EmployeeB = employeeB };
    
            foreach (var queryResult in identicalQuery)
            {
                Console.WriteLine(queryResult.EmployeeA.Name);
                Console.WriteLine(queryResult.EmployeeB.Name);
            }
    

提交回复
热议问题