Mech_Engineer
Mech_Engineer

Reputation: 555

vb.net sorting list(of T) based on class property

I'm currently working on a project that implements the usage of a List(of T). And i'm trying to sort the list.

The collection is based on class PDF_Document

Public Class PDF_Document
    Public FullFilePath As String
    Public Property Size As String
    Public Property DocNumber As String
    Public Property Sequence As String
    Public Property Revision As String
End Class

When the collection is filled, it should sort the collection on the sequence number. 001, 002, 003, 004, ...

But how do you sort a collection based on that property?

Upvotes: 1

Views: 1993

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460098

Why do you store such a number as string at all? If you want to diplay that number formatted with leading zeros, format it when you diplay it, f.e. with sequence.ToString("D3") but don't store it as string.

If you want to sort the original list you can use List(Of T).Sort:

pdfList.Sort(Function(pdf1, pdf2)
                 Return pdf1.Sequence.CompareTo(pdf2.Sequence)
             End Function)

If you don't want to modify the original list you can use LINQ:

Dim ordered = From pdf In pdfList Order By pdf.Sequence

You can create a new list with ToList, f.e.:

Dim orderedPdfList = ordered.ToList()

Otherwise you always have to parse the string to Int32:

Dim ordered = From pdf In pdfList Order By Int32.Parse(pdf.Sequence)

Upvotes: 2

Related Questions