博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

过滤泛型中重复的数据

Posted on 2011-12-20 11:38  sigo-yr  阅读(194)  评论(0编辑  收藏  举报

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/>");
}



流量统计