Question Sorting a List in a RichTextBox by the Date Inside

digitaldrew

Well-known member
Joined
Nov 10, 2012
Messages
167
Programming Experience
Beginner
I'm wanting to do something, but not really sure if this can be done or how it can be done...

I have a list like this:
VB.NET:
example0 2010
example1 1999
example2 2006
example3 1989
example4 2014

and I would like to arrange the list using the date at the end. So, it should be like this:
VB.NET:
example3 1989
example1 1999
example2 2006
example0 2010
example4 2014

I'm not really sure how I would go about doing this with the date being at the end. Also, the initial string (example) will not always be the same length. The list is being generated into a RichTextBox. Ideally, I am wanting to sort these as they are put into the RichTextBox, or afterwards when saving into a text file. Any help or suggestions would be greatly appreciated..
 
Last edited by a moderator:
Why are you using a RichTextBox in the first place? It's not really for displaying lists. It exists for displaying and editing RTF formatted text. Is the user entering text directly into the control? Can they not, for instance, enter the data using a simple TextBox and a DateTimePicker for the year, then click a Button to have the data entered into a property list or grid control, like a ListBox, ListView or DataGridView?

If you really want to stick with the RichTextBox, you would start by getting the Lines property, which will return a String array. You can then manipulate that data as required to sort it, which could be done in numerous ways, all of which can be found on the web in various places, then recombine the data into a String array and assign that back to the Lines property.
 
If you already have the lines (from your data or from RichTextBox), you can use Linq and Regex to sort them. Regex may depend on what the preceding strings can be, but if the 4 year digits is exclusive it can be done like this:
VB.NET:
Dim sorted = From line In lines Order By CInt(Regex.Match(line, "\d{4}").Value)
 
Back
Top