Rah*_*hul 6 c# comparison compare object automapper
我需要创建一个泛型方法,它将获取两个对象(相同类型),并返回具有不同值的属性列表.由于我的要求有点不同,我不认为这是重复的.
public class Person
{
public string Name {get;set;}
public string Age {get;set;}
}
Person p1 = new Person{FirstName = "David", Age = 33}
Person p2 = new Person{FirstName = "David", Age = 44}
var changedProperties = GetChangedProperties(p1,p2);
Run Code Online (Sandbox Code Playgroud)
该代码解释了该要求:
public List<string> GetChangedProperties(object A, object B)
{
List<string> changedProperties = new List<string>();
//Compare for changed values in properties
if(A.Age != B.Age)
{
//changedProperties.Add("Age");
}
//Compare other properties
..
..
return changedProperties;
}
Run Code Online (Sandbox Code Playgroud)
应考虑以下事项:
那里有没有开箱即用的图书馆?
我可以使用AutoMapper实现这一目标吗?
我对克里希纳斯的回答有所改善:
public List<string> GetChangedProperties<T>(object A, object B)
{
if (A != null && B != null)
{
var type = typeof(T);
var allProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var allSimpleProperties = allProperties.Where(pi => pi.PropertyType.IsSimpleType());
var unequalProperties =
from pi in allSimpleProperties
let AValue = type.GetProperty(pi.Name).GetValue(A, null)
let BValue = type.GetProperty(pi.Name).GetValue(B, null)
where AValue != BValue && (AValue == null || !AValue.Equals(BValue))
select pi.Name;
return unequalProperties.ToList();
}
else
{
throw new ArgumentNullException("You need to provide 2 non-null objects");
}
}
Run Code Online (Sandbox Code Playgroud)
因为它不适合我.这个,并且你需要使它工作的唯一另一件事是IsSimpleType() - 扩展方法,我在这里改编自这个答案(我只将其转换为扩展方法).
public static bool IsSimpleType(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// nullable type, check if the nested type is simple.
return type.GetGenericArguments()[0].IsSimpleType();
}
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
}
Run Code Online (Sandbox Code Playgroud)