C#: Getting the dates from file names

Getting the dates from file names.

using System.Linq;
using System.Collections.Generic;
class Test
{
    static void Main()
    {
        var items = new List<string>() {
                "foo_20120212",
                "foo_20120213",
                "foo_20120214",
                "foo_20120215",
                "baz_20120212",
                "baz_20120213",
                "baz_20120214",
                "baz_20120215"};

        var v = items.Select(a => a.Insert(a.Length - 2, "/"))
                                .Select(b => b.Insert(b.Length - 5, "/"))
                                .Select(c => new { date = c.Split('_')[1], str = c.Replace("/", "") })
                                .Select(d => new { date = String.Concat(d.date.Split('/').Reverse()), str = d.str })
                                .Select(e => new { date = e.date.Insert(e.date.Length - 4, "/"), str = e.str })
                                .Select(f => new { date = f.date.Insert(f.date.Length - 7, "/"), str = f.str })
                                .Select(g => new { date = DateTime.Parse(g.date), str = g.str })
                                .OrderByDescending(h => h.date).ToList();

        v.ForEach(x => Console.WriteLine(String.Format("date: {0}, str: {1}", x.date, x.str)));
        Console.ReadKey();
    }
}

date

Leave a comment

Leave a Reply