我有以下实体
public class Employee
{
public int EmpId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何比较对象?谢谢
IEquatable<T>在您的类型上实现(在本例中Employee),然后使用Enumerable.SequenceEqual:
bool equal = Enumerable.SequenceEqual(lst1, lst2);
Run Code Online (Sandbox Code Playgroud)
如果您不能修改Employee类,你还可以创建自定义IEqualityComparer<T>的Employee,并使用其他超载Enumerable.SequenceEqual.
bool equal = lst1.SequenceEqual(lst2, new EmployeeComparer());
Run Code Online (Sandbox Code Playgroud)
请注意,只有当两个集合包含相同顺序的相同对象时,才会认为它们相等.
如果项目的顺序无关紧要,我会使用这样的东西:
bool equal = lst1.Count == lst2.Count && lst1.Count == lst1.Intersect(lst2).Count();
Run Code Online (Sandbox Code Playgroud)
你也可以使用一个IEqualityComparer<T>具有Intersect.
更新:
看起来你希望能够比较任何对象,即使它们没有实现IEquatable<T>.下面是一个相等比较器的示例,IEquatable<T>如果它是可用的,将使用它,Enumerable.SequenceEqual如果类型是一个集合,否则使用反射以递归方式检查该类型的公共属性:
class ReflectionComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
Type type = typeof(T);
if( typeof(IEquatable<T>).IsAssignableFrom(type) )
return EqualityComparer<T>.Default.Equals(x, y);
Type enumerableType = type.GetInterface(typeof(IEnumerable<>).FullName);
if( enumerableType != null )
{
Type elementType = enumerableType.GetGenericArguments()[0];
Type elementComparerType = typeof(ReflectionComparer<>).MakeGenericType(elementType);
object elementComparer = Activator.CreateInstance(elementComparerType);
return (bool)typeof(Enumerable).GetMethod("SequenceEqual")
.MakeGenericMethod(elementType)
.Invoke(null, new object[] { x, y, elementComparer });
}
foreach( PropertyInfo prop in type.GetProperties() )
{
Type propComparerType = typeof(ReflectionComparer<>).MakeGenericType(prop.PropertyType);
object propComparer = Activator.CreateInstance(propComparerType);
if( !((bool)typeof(IEqualityComparer<>).MakeGenericType(prop.PropertyType)
.GetMethod("Equals")
.Invoke(propComparer, new object[] { prop.GetValue(x, null), prop.GetValue(y, null) })) )
return false;
}
return true;
}
public int GetHashCode(T obj)
{
throw new NotSupportedException();
}
}
Run Code Online (Sandbox Code Playgroud)
我没有实施,GetHashCode因为它不需要Enumerable.SequenceEqual.
这应该能够做你想要的(但要注意这不是完全有效的;不要在性能关键代码中使用它).
| 归档时间: |
|
| 查看次数: |
485 次 |
| 最近记录: |