列表(T)对自定义类的成员进行排序?

时间:2012-10-16 16:54:40

标签: vb.net

如何在一个成员(整数)上对一个列表(T)进行排序,其中T是一个自定义数据类?

Public Class CustomObject
   Public Property text1 as String
   Public Property counter1 as Integer
   Public Property counter2 as Integer
End Class

Public Objectlist As New List(Of CustomObject)

.add, .add, .add etc.

Objectlist.sort(???...)

1 个答案:

答案 0 :(得分:2)

您可以使用Sort overload which takes a predicate

执行此操作
ObjectList.Sort(Function(i,j) i.counter1.CompareTo(j.counter1))

请注意,您还可以使用LINQ返回新对象:

 Dim sorted = ObjectList.OrderBy(Function(i) i.counter1)

如果您需要降序排序,可以执行以下操作:

ObjectList.Sort(Function(i,j) j.counter1.CompareTo(i.counter1))

或者:

 Dim sorted = ObjectList.OrderByDescending(Function(i) i.counter1)