1

I have two list declared as

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

Now each element of Item2 contains elements of Item

Now Item has 4 elements

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"

Now I want to sort Item2 according to field "Bin" and then field "Item" in Item

so that Item2 contains item according to the order of field "Bin" and then field "Item" in Item

How to do this?

2
  • This sounds like you should create a class or struct for your objects and just create a List(Of MyClass). Have you considered this? You could then implement a comparer that specifies how to sort. Commented Feb 10, 2013 at 16:50
  • no i have not created the class Commented Feb 10, 2013 at 16:57

1 Answer 1

1

You simply need to create a class. We can also harness one of .Net's built-in datastructures, the SortedList. In order to use the sorted list, your class needs to implement iComparable, which I will cover below.

Class Product
  public Item as string
  public Descrip as string
  public Price as decimal
  public Bin as string
end class

Now, your class needs to implement iComparable

We'll modify the class as follows

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

Now, you should use a SortedList(of Product)

You add elements to it like 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 always keeps its elements in order.

The code above can be optimized some, but I think you get the picture.

References

Sign up to request clarification or add additional context in comments.

1 Comment

yes sir but i want to sort item according to the bin element and in the Item2 List

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.