List對象去重

public class Userspa

{
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
}get

//使用示例string

protected void Page_Load(object sender, EventArgs e)
{it

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()); //去重複 
}io

相關文章
相關標籤/搜索