首页 > 解决方案 > 如何比较具有相同属性的两个视图模型,如果属性的值不同,则将该属性添加到不同的列表中?

问题描述

可以说我有两个视图模型。

查看模型 1:

public string Name {get;set;} = Harry
public int Age {get;set;} = 19
public string Address {get;set;} = Somewhere
public string PhoneNumber {get;set;} = 1234567899

查看模型 2:

public string Name {get;set;} = Harry
public int Age {get;set;} = 19
public string Address {get;set;} = Here
public string PhoneNumber {get;set;} = 1234567899

所以你可以看到属性地址的值是不同的。我的问题是我们如何比较这两个视图模型,如您所见,地址值不同,在比较这两个视图模型后,我需要将 Address 属性添加到列表中。

标签: c#

解决方案


如果您需要一个差异列表,您可以使用它:(其中 Model 是您的View Model 类

public static List<string> GetDifferences(Model first, Model second) =>
    typeof(Model).GetProperties()
        .Where(property => property.GetValue(first) != property.GetValue(second))
        .Select(property => property.Name)
        .ToList();

没有 LINQ 的相同方法:

public static List<string> GetDifferences(Model first, Model second)
{
    var result = new List<string>();

    foreach (var property in typeof(Model).GetProperties())
    {
        if (property.GetValue(first) != property.GetValue(second))
        {
            result.Add(property.Name);
        }
    }

    return result;
}

推荐阅读