public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class UserComparer : IEqualityComparer<User>
{
#region IEqualityComparer<User> 成员
public bool Equals(User x, User y)
{
if (x == null && y == null)
{
return false;
}
return x.Id == y.Id;//根据id去重
}
public int GetHashCode(User obj)
{
return obj.ToString().GetHashCode();
}
#endregion
}
//使用示例
protected void Page_Load(object sender, EventArgs e)
{
List<User> list = new List<User>(); //添加一些测式数据
list.Add(new User { Id = 1, Name = "张三" });
list.Add(new User { Id = 2, Name = "小伟" });
list.Add(new User { Id = 1, Name = "张三" });
list.Add(new User { Id = 3, Name = "李三" });
list.Add(new User { Id = 2, Name = "李四" });
list.Add(new User { Id = 1, Name = "李武" });
var query = list.Distinct(new UserComparer()); //去重复
}