c# - 如何比较具有相同属性的两个视图模型,如果属性的值不同,则将该属性添加到不同的列表中?
问题描述
可以说我有两个视图模型。
查看模型 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 属性添加到列表中。
解决方案
如果您需要一个差异列表,您可以使用它:(其中 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;
}
推荐阅读
- c# - 在 ASP.NET Core 中使用 SQL 视图的数据访问如何更好地构建模型?
- pandas - 我想对数据透视表进行多级排序
- azure-data-factory - Azure 数据工厂查找活动在读取有空格的列名时出现问题
- javascript - 为什么会出现错误:React.Children.only 期望接收单个 React 元素子元素。?
- spring-boot - Spring boot 2.4 - 必须在构建器或设置环境中提供显式区域以提供区域
- pandas - 熊猫分析相关警告似乎是错误的
- php - 路由登录未定义,如果管理员用户当前未登录,我在尝试将页面重定向到登录时不断收到此错误
- c - 装配中的缓冲器
- excel - 如何将一张表中的单元格内容动态复制到另一张表中?
- laravel - Livewire 复选框数组仅保存最后点击的值