你有一个list,格式如list<userType>, 但是这个userType并没有继承自ICompare或者IComparable 等,那如何给这个list排序那?
指定一个类 这个类要继承自ICompare<userType>
如
然后:
指定一个类 这个类要继承自ICompare<userType>
如
public class SortUserGroup:IComparer<UserGroup>
{
/// <summary>
/// Sort by AccountID and UserGroupName
/// </summary>
/// <param name="userGroup1"></param>
/// <param name="userGroup2"></param>
/// <returns></returns>
int IComparer<UserGroupEntityAccess>.Compare(UserGroup userGroup1, UserGroup userGroup2)
{
if (userGroup1 != null && userGroup2 != null)
{
if (userGroup1.AccountID == userGroup2.AccountID)
return userGroup1.UserGroupName.CompareTo(userGroup2.UserGroupName);
else
return userGroup1.AccountID > userGroup2.AccountID ? 1 : -1;
}
return -1;
}
}
{
/// <summary>
/// Sort by AccountID and UserGroupName
/// </summary>
/// <param name="userGroup1"></param>
/// <param name="userGroup2"></param>
/// <returns></returns>
int IComparer<UserGroupEntityAccess>.Compare(UserGroup userGroup1, UserGroup userGroup2)
{
if (userGroup1 != null && userGroup2 != null)
{
if (userGroup1.AccountID == userGroup2.AccountID)
return userGroup1.UserGroupName.CompareTo(userGroup2.UserGroupName);
else
return userGroup1.AccountID > userGroup2.AccountID ? 1 : -1;
}
return -1;
}
}
然后:
SortUserGroup sortGroup = new SortUserGroup();
List<UserGroup>.Sort(sortUserGroup)
这里是按照UserGroup的AccountID 和 UserGroupName 两个字段排序。