1.先为要过滤的数据做个实体类:User
public class User
{
public User(int id, string name)
{
Id = id;
Name = name;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
2.再自定义一个User比较类(实现IEqualityComparer<T>接口):RemoveRepeatList
public class RemoveRepeatList : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
if (x.Id == y.Id && x.Name == y.Name)
return true;
else
return false;
}
public int GetHashCode(User obj)
{
return 0;
}
}
public class User
{
public User(int id, string name)
{
Id = id;
Name = name;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
3.调用测试用例:
List<User> list = new List<User>();
list.Add(new User(1, "张三"));
list.Add(new User(1, "李三"));
list.Add(new User(1, "小伟"));
list.Add(new User(1, "李三"));
list.Add(new User(2, "李四"));
list.Add(new User(2, "李武"));
var query = list.Distinct(new RemoveRepeatList());
foreach (var item in query)
{
Response.Write("键:" + item.Id + " " + "值:" + item.Name + "<br/>");
}