C# List列表 去重和排序


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);
當然排序還有其他幾種實現方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM