问题描述
我想在多个属性上对对象的Arraylist进行排序。对于
实例,我有一个Sort Index属性和一个ID属性(都是整数)。
所以,我的排序结果如下:
排序索引,id
1000,1
1000,2
1000,3
1001,1
1001,2
....
我知道我可以实现IComparable.CompareTo到在一个属性上排序,但是我不知道如何对两个属性进行排序。感谢您的帮助。
为什么在没有必要时创建字符串?他需要做的就是在CompareTo方法中首先检查索引的值。如果他们
不相等,那么就对索引进行比较。如果索引是
等于,那么对ID进行比较:
如果索引不相等,那么Id的值将赢得''无论如何都会影响
排序。
如果obj1.Index< obj2.Index那么
返回obj1.Index.CompareTo (Obj2.Index)
否则
返回obj1.Id.CompareTo(obj2.Id)
结束如果
I would like to sort an Arraylist of objects on multiple properties. For
instance, I have a Sort Index property and an ID property (both integers).
So, the results of my sort would look like this:
sort index, id
1000,1
1000,2
1000,3
1001,1
1001,2
....
I know I can implement IComparable.CompareTo to sort on one property but I
am not completely clear on how to sort on two. Thanks for any help.
Why create strings when it is not necessary? All he needs to do is in
the CompareTo method to first check the value of the index. If they
are not equal then do the compare on the index. If the indexes are
equal, then do the compare on the ID:
If the indexes are not equal, then the value of the Id won''t affect the
sort anyway.
If obj1.Index <obj2.Index Then
return obj1.Index.CompareTo(Obj2.Index)
Else
return obj1.Id.CompareTo(obj2.Id)
End If
这篇关于排序对象的Arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!