C# 列表>> 具有 3 个属性的订单 .Net 2.0
假设我有一个包含 Name、Age、Level 属性的 Person 类。
我知道如何按其中一项属性进行排序,
PersonList.Sort(delegate(Person p1, Person p2) {
return p1.Name.CompareTo(p2.Name);
});
但是我如何按姓名、年龄和级别进行排序。
sql语句的等价物:ORDER BY Name, Age, Level
谢谢
Say I have a Person class with Name, Age, Level properties.
I know how to order by one of the properties, with
PersonList.Sort(delegate(Person p1, Person p2) {
return p1.Name.CompareTo(p2.Name);
});
But how can I order by Name, Age and Level.
An equivalente of the sql sentence : ORDER BY Name, Age, Level
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
调整您当前的代码:
或者,一个简单的 linq-ish 解决方案:
Adapting your current code:
or, a simple linq-ish solution:
您是否考虑过切换到 .NET 3.5 并使用 LINQ? 在 LINQ 中,这样的事情非常简单:
Have you considered switching to .NET 3.5 and using LINQ? Things like this are really easy in LINQ:
我会在您的 Person 类上实现 IComparable 。 在自定义比较方法中,您可以设置对所有三个属性进行比较的逻辑,并确保这三个属性具有适当的“权重”(例如,如果 Person 的两个实例具有相同的名称,您应该按 Age 或 Level 进行下一步排序)。
I would implment IComparable on your Person class. In your custom compare method, you can set the logic to compare on all three properties, and make sure the three have the proper "weight" (e.g., if two instances of Person have the same name, should you sort next on Age or Level).
假设您使用的是 .NET 3.5
Assuming you are using .NET 3.5
如果您有可用的 C# 3.0(LINQ 支持),那么您可以执行以下操作:
If you have C# 3.0 available (LINQ support), then you can do the following:
您考虑过 LINQ to Objects 吗?
Have you considered LINQ to Objects?
您需要对要排序的第一个属性调用 CompareTo,获取返回的值,如果为 0,则对下一个属性调用 CompareTo,并重复,每次返回 0 时,继续处理下一个属性直到获得非零值(然后返回该值)或者到达要排序的属性的末尾。
You need to call CompareTo on the first property you want to order by, get the value that is returned, and if it is 0, then call CompareTo on the next property, and repeat, each time 0 is returned, continue onto the next property until you get a non-zero value (which you then return) or you get to the end of the properties you want to sort by.