List<Data> list = new List<Data>();
list.Add(new Data { Email = "123", Remark = "345" });
list.Add(new Data { Email = "abc", Remark = "456" });
list.Add(new Data { Email = "abc", Remark = "456" });
list.Add(new Data { Email = "abc", Remark = "789" });
//问题1:根据字段去重
//方法1
public class Data:IEquatable<Data>
{
public string Email { get; set; }
public string Remark { get; set; }
public bool Equals( Data other)
{
return this.Email == other.Email;//根据某个或多个字段去重
}
public override int GetHashCode()
{
return Email.GetHashCode();
}
}
List<Data> ll = list.Distinct().ToList();
//方法2
public class UserComparer : IEqualityComparer<Data>
{
public bool Equals(Data x, Data y)
{
if (x == null && y == null)
{
return false;
}
return x.Email.ToUpper() == y.Email.ToUpper();
}
public int GetHashCode(Data obj)
{
return obj.ToString().GetHashCode();
}
}
List<Data> l2 = list.Distinct(new UserComparer()).ToList();
//方法3
List<Data> l3 = list.Where((x, i) => list.FindIndex(z => z.Email == x.Email) == i).ToList();
//问题2:去重完全相同的对象
//方法1
var list1 = list.Select(a => new { Email = a.Email, ReMark = a.Remark }).Distinct();
//方法2
var list2 = (from q in list
select new
{
Email = q.Email,
Remark = q.Remark
}).Distinct();