Link to home
Start Free TrialLog in
Avatar of Miguel Oz
Miguel OzFlag for Australia

asked on

How to order IEnumerable<string> in date ascending order?

I have the results of Directory.EnumerateFiles as follows: (date is YYYYMMDD format)
c:\download\20160912\target.csv
c:\download\20160915\target.csv
c:\download\20160914\target.csv
c:\download\20160913\target.csv

I would like to order in date ascending order:
c:\download\20160912\target.csv
c:\download\20160913\target.csv
c:\download\20160914\target.csv
c:\download\20160915\target.csv
c:\download\20160917\target.csv

Note: C# or VB.NET code is OK. please add you code as a method so it is easier to test and provide speedy feedback.

Thanks,
SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Personally I would use a regular expression to pull the date from the string in order to convert it to a DateTime type, then I would order based on the DateTime results; e.g. -
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

namespace EE_Q28971220
{
	class Program
	{
		static readonly List<string> files = new List<string>() 
		{ 
			@"c:\download\20160912\target.csv", 
			@"c:\download\20160915\target.csv", 
			@"c:\download\20160914\target.csv", 
			@"c:\download\20160913\target.csv", 
			@"c:\download\20160917\target.csv" 
		};

		static void Main(string[] args)
		{
			foreach (var file in files.OrderBy(x => x.GetDate()))
				Console.WriteLine(file);
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static DateTime GetDate(this string path)
		{
			DateTime result = DateTime.MinValue;
			Regex expression = new Regex("\\\\(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))\\\\");
			var match = expression.Match(path);
			if (match != null)
				DateTime.TryParseExact(match.Value, "\\\\yyyyMMdd\\\\", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out result);
			return result;
		}
	}
}

Open in new window

Produces the following output -User generated image
-saige-
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Miguel Oz

ASKER

Thanks Guys and good point Gustav. Your solution is much smpler
You are welcome!

/gustav