public class User
{
private String _userId;
private String _userName;
public String userId
{
get{return _useId;}
set{_userId = value;}
}
public String userName
{
get{return _userName;}
set{_userName = value;}
}
}
1.对List列表去重:
//List_User_DistinctBy_userId比较器,继承自IEqualityComparer接口。
public class List_User_DistinctBy_userId:IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
if (x.userId == y.userId)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(User obj)
{
return 0;
}
}
使用:
List<User> UserList = new List<User>(); //初始化
……
UserList .Add(user1);
……
if(UserList.Count > 0)
{
UserList = UserList.Distinct(new List_User_DistinctBy_userId()).ToList();
}
2.排序
private static int SortUserByName(User a, User b)
{
if((a==null) && (b==null))
return 0;
else if((a!=null) && (b==null))
return 1;
else if((a==null) && (b!=null))
return -1;
else
return a.userName.CompareTo(b.userName);
}
使用:
UserList.Sort(SortUserByName);
当然排序还有其他几种实现方法。