2013-02-10 85 views
1

我有兩個列表聲明爲如何另一個列表內vb.net排序列表

Dim Item As New List(Of String) 
    Dim Item2 As New List(Of Array) 

現在項目2的每個元素包含項的元素

現在項目有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" 

現在我想根據現場「賓」排序項目2,然後在項目

所以日場「項目」在項目2包含項目,根據項目「斌」的順序,然後項目中的項目「項目」

如何做到這一點?

+0

這聽起來像是你應該爲你的對象類或結構,只是創造一個'清單(中MyClass的)'。你有沒有考慮過這個?然後可以實現一個指定如何排序的比較器。 – 2013-02-10 16:50:19

+0

不,我沒有創建類 – Somdeb 2013-02-10 16:57:50

回答

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)

你添加元素給它l ike this

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總是保持其元素的順序。

上面的代碼可以優化一些,但我認爲你得到的圖片。

參考

+0

是的先生,但我想根據bin元素和Item2列表進行排序 – Somdeb 2013-02-10 18:07:03