1、比较集合
/// <summary>
/// 比较两个集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns></returns>
public static bool EqualList<T>(this List<T> list1, List<T> list2)
{
return list1 == null && list2 == null || list1 != null && list1.SequenceEqual(list2);
}
2、比较对象,对象实现IEquatable接口
public class Model: IEquatable<Model>
{
public int Id { get; set; }
public string Name { get; set; }
public List<string> List { get; set; }
public bool Equals(Model obj)
{
//this非空,obj如果为空,则返回false
if (ReferenceEquals(null, obj)) return false;
//如果为同一对象,必然相等
if (ReferenceEquals(this, obj)) return true;
//如果类型不同,则必然不相等
if (obj.GetType() != GetType()) return false;
//对比各个字段值
if (!Equals(Id, obj.Id) || !Equals(Name, obj.Name) || !List.EqualList(obj.List))
return false;
//如果基类不是从Object继承,需要调用base.Equals(other)
//如果从Object继承,直接返回true
return true;
}
public override int GetHashCode()
{
return StringComparer.InvariantCulture.GetHashCode(Id);
}
}