namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<User> users = new List<User>();
users.Add(new User() { UserId = 1, UserName = "1" });
users.Add(new User() { UserId = 2, UserName = "2" });
users.Add(new User() { UserId = 3, UserName = "3" });
users.Sort();
foreach (var u in users)
{
Console.Write(u.UserName);
}
Console.Read();
}
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
}
上面这段代码,在users.Sort();会抛异常。
要使结果输出123,在不修改User类的情况下,代码要如何改动?
要使结果输出321,在只能改动User类的情况下,代码要如何改动?
请各位大神指教指教
1.要使结果输出123,在不修改User类的情况下,代码要如何改动?
users.Sort((x, y) => x.UserId - y.UserId);
2.要使结果输出321,在只能改动User类的情况下,代码要如何改动?
users.Sort();
public class User: IComparable<User>
{
public int UserId { get; set; }
public string UserName { get; set; }
public int CompareTo(User other)
{
return other.UserId - UserId;
}
}
大神厉害啊,谢谢啦。能给我解释一下输出321的那段代码的原理吗?
users.orderby(p=>p.usreid) //asc
users.orderbydesc(p=>p.usreid) //desc