使用 CompareTo() 根据多列进行排序
目前我有一个实现 IComparable 接口的对象(ASP.NET 3.5,VB)。 当我将几个实例化对象放入泛型列表中时,我通过执行简单的 someList.Sort
对它们进行排序。 我的 CompareTo()
函数是这样的:
Public Function CompareTo(ByVal obj As Object) As Integer Implements
System.IComparable.CompareTo
'default is number of votes (opposite direction, highest first)'
Dim sent As Sentence = CType(obj, Sentence)
Return Not Points.CompareTo(sent.Points)
End Function
这工作得很好,只是现在我需要按另一个属性(DateSubscribed 属性)作为 Points 的子集进行排序。 例如,如果三个句子有投票:3、1、1,我希望将得票最高的句子放在第一位(显然),而在只有一票的两个句子中,最早提交的句子会被列出。
这可以通过 CompareTo() 实现吗?或者我应该再次访问数据库并在那里对其进行排序?
谢谢
Currently I have an object implementing the IComparable interface (ASP.NET 3.5, VB). When I place several instantiated objects into a Generics list, I sort them by doing a simple someList.Sort
. My CompareTo()
function is this:
Public Function CompareTo(ByVal obj As Object) As Integer Implements
System.IComparable.CompareTo
'default is number of votes (opposite direction, highest first)'
Dim sent As Sentence = CType(obj, Sentence)
Return Not Points.CompareTo(sent.Points)
End Function
This works fine, except now I need to sort by another property, the DateSubmitted property, as a subset of the Points. For example, if three sentences have votes: 3, 1, 1, I want the one with the highest votes first (obviously) and of the two sentences with one vote, the one submitted the earliest to be listed.
Is this possible with CompareTo(), or should I just hit the database again and sort it there?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 CompareTo() 函数不正确。 您需要为三种状态(<、= 和 >)返回正确的结果,而您的
Not
意味着该函数只能正确处理其中两种状态。 如果您在足够大的列表上调用该函数,这将导致问题。正如 MehrdadA 已经提到的,.Net 3.5 有一种更简单的方法来处理它。 但如果由于某种原因您无法处理 lambda 表达式,请执行以下操作:
请注意,您现在想要实现
IComparable(Of T)
,而不是IComparable
。Your CompareTo() function is incorrect. You need to return correct results for three states (<, =, and >), and your
Not
means the function only correctly handles two of them. This will cause problems if you call the function on a large enough list.As MehrdadA already mentioned, .Net 3.5 has a simpler way to handle it. But here's how to do it if for some reason you can't handle the lambda expressions:
Note that you now want to implement
IComparable(Of T)
, rather thanIComparable
.由于您使用的是 .NET 3.5,因此您可以轻松地使用
OrderBy
扩展方法进行排序:是否应该再次访问数据库取决于您最初检索数据的方式。 如果您有一个大型数据集,并且只从数据库中检索了其中的一小部分,那么不可以,您应该只要求数据库根据新的排序顺序获取一小部分数据。 否则,如果您已经记住了整个内容,请按照我上面提到的方式对其进行排序。
Since you're on .NET 3.5, you can sort using the
OrderBy
extension method easily:Whether you should hit the database again or not depends on how you've retrieved data in the first place. If you have a large data set and you had retrieved only a small subset of it from the DB, then no, you should just ask the DB to grab a small subset of data based on the new sort order. Otherwise, if you already have the whole thing in memory, just sort it as I mentioned above.