c#比较两个List <t>显示添加,删除和属性更改

时间:2017-07-06 14:31:26

标签: c# reflection system.reflection

我有两个myObj类型的列表定义如下:

public class myObj
{
    public int Id {get;set;}
    public string Name {get;set}
    public Address Address {get;set;}
}

这使用另一个名为Address

的类
public class Address
{
    public int Id {get;set;}
    public string Line1 {get;set}
    public string ZipCode {get;set;}
}

我有一个主要的子组件如下。

sub Main()
{
    var myTestObj1 = new List<myObj>(
        new myObj(){ Id = 1, Name = "Bob", new Address(){ Id = 1, Line 1= "", ZipCode = "90120"}},
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "90121"}}
    );
    var myTestObj2 = new List<myObj>(
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "00121"}}
        new myObj(){ Id = 3, Name = "Suz", new Address(){ Id = 3, Line 1= "", ZipCode = "99999"}}
    );
}

我需要做的是检查列表中的差异。从上面,我正在寻找以下内容。

寻找myTestObj1和myTestObj2

之间的区别

我希望看到:

myObj id = 1 = New Record
myObj id = 2 = ZipCode has Changed
myObj id = 3 = Record to be deleted

到目前为止,我已经考虑过使用反射,但是示例只显示了一对一的比较。

C# Compare Two Lists of Different Objects

Difference between two lists

Compare two List objects for equality, ignoring order

如果这是重复的,有人可以指出在哪里找到解决方案,因为我已经看了几个小时。

由于

1 个答案:

答案 0 :(得分:0)

非常感谢您的建议,但最后我选择了一种更简单的方法。

我在viewmodel中添加了一个新属性,该属性包含添加,删除,更新或无更改的枚举值。视图将此字段添加为隐藏输入。然后通过一些java脚本更新它。