我将两个列表声明为
Dim Item As New List(Of String)
Dim Item2 As New List(Of Array)
现在,Item2的每个元素都包含Item
的元素现在Item有4个元素
Item.Add(String.Format(record(0))) ' Field "Item"
Item.Add(String.Format(record(1))) ' Field "Descrip"
Item.Add(String.Format(record(2))) ' Field "Price"
Item.Add(String.Format(record(3))) ' Field "Bin"
现在我想根据字段“Bin”对Item2进行排序,然后在Item
中对字段“Item”进行排序以便Item2根据字段“Bin”的顺序包含项目,然后在Item
中包含字段“Item”怎么做?
答案 0 :(得分:1)
您只需要创建一个类。我们还可以利用.Net的内置数据结构之一SortedList。为了使用排序列表,您的类需要实现iComparable,我将在下面介绍。
Class Product
public Item as string
public Descrip as string
public Price as decimal
public Bin as string
end class
现在,您的班级需要实施iComparable
我们将按如下方式修改课程
Class Product
Implements IComparable
public Item as string
public Descrip as string
public Price as decimal
public Bin as string
Public Overloads Function CompareTo(ByVal obj As Object) As Integer
if obj is nothing then return 1
Dim otherObj As Product = TryCast(obj, Product)
If otherObj IsNot Nothing Then
if me.bin < otherObj.bin then
return -1
else if me.bin = otherObj.bin andalso me.item < otherObj.item then
return -1
elseif me.bin = otherObj.bin andalso me.item = otherObj.item then
return 0
else
return 1
Else
Throw New ArgumentException("Object is not a Product")
End If
End Function
end class
现在,您应该使用SortedList(of Product)
您可以像这样添加元素
Dim MyProduct as NewProduct
MyProduct.bin = "test"
MyProduct.price = 12.0D
MyProduct.item = "test"
MyProduct.descrip = "test"
Dim MySortedList = new SortedList(of Product)
MySortedList.add(NewProduct)
MySortedList始终按顺序保留其元素。
上面的代码可以进行一些优化,但我认为你得到了图片。
<强>参考强>