0

I have created an array from a CSV of date values and now need to be able to sort them so that I can then get the latest date from the array.

I have tried:

Array.Sort()

but this doesn't sort correctly, I suppose because the array values are strings, any body got any ideas??

Thanks for any help.

CODE USED TO CREATE ARRAY

'array string exampel: "19/07/2012,23/07/2012,23/07/2012,19/07/2012,25/07/2012"
Dim ArrDates As Array = ArrDates .Split(",")

SOLUTION

Dim ArrAgentsReportCheck As Array = AgentsReportCheck.Split(",")

Dim ArrDates As New List(Of Date)
For i As Integer = 0 To ArrAgentsReportCheck.Length - 1
    ArrDates.Add(ArrAgentsReportCheck(i))
Next

ArrDates.Sort()
Dim LatestDate As Date = ArrDates.Max()
6
  • Create a List (not Array) of DateTime objects (not strings). You can use DateTime.TryParse/TryParseExact to convert the strings to DateTimes, and then use the Sort Method. Commented Aug 7, 2013 at 11:55
  • Show us an exemplary string that you want to convert to date. Commented Aug 7, 2013 at 11:55
  • Code used to load the array and the format of the strings (to be interpreted as dates) should be very helpful here Commented Aug 7, 2013 at 11:56
  • thanks for replies, added in example of dates string and how its converted to array. Commented Aug 7, 2013 at 12:09
  • As others have said make a List(of DateTime) instead and then you can use Max() on it to get the largest value (ie latest date). If getting the latest date is all you want then you don't need to sort the whole list so Max will be quicker. Commented Aug 7, 2013 at 12:21

3 Answers 3

3
ArrDates = ArrDates.OrderBy(Function(d) DateTime.ParseExact(d, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)).ToArray()

Alternately, you can use OrderByDescending() depending upon your needs.

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

Comments

2

As astander said, It is very complicated to sort a array having datetime values. Instead just convert the array to List or ArrayList and make your life easy.

For ArrayList you can use the following syntax:

List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();

Comments

1

One way would be to convert strings to DateTime using DateTime.ParseExact

Another way just to write your own IComparer and pass to Array.Sort

Comments

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.