Sort part of a list in descending order (by date), the other part in ascending order (alphabetically)?

I would create a custom class that parses out the date and the rest of the filename in to separate properties, you can then use OrderByDescending and ThenBy to sort on these individual properties.

public class ParsedFilename
{
    public ParsedFilename(string filename)
    {
        FullName = filename;
        if (filename.Length >= 12 &&
            DateTime.TryParse(filename.Substring(0, 10), out var date))
        {
            Date = date;
            Name = filename.Substring(11);
        }
        else
        {
            Date = null;
            Name = filename;
        }
    }

    public DateTime? Date { get; }
    public string Name { get; }
    public string FullName { get; }
}

You can use it like this:

var data = new List<string>(new[]
    {
        "2019-01-12 Meeting minutes.pdf",
        "Safeguarding policy.pdf",
        "2017-04-27 Meeting minutes.pdf",
        "2018-06-02 Meeting minutes.pdf",
        "2017-12-13 Meeting agenda.pdf",
        "Privacy policy.pdf",
        "Welfare policy.pdf",
        "2018-11-19 Meeting agenda.pdf"
    });

var parsedData = data.Select(d => new ParsedFilename(d));

var sortedData = parsedData.OrderByDescending(d => d.Date)
                           .ThenBy(d => d.Name);

var output = sortedData.Select(d => d.FullName);

It produces the following output:

2019-01-12 Meeting minutes.pdf
2018-11-19 Meeting agenda.pdf
2018-06-02 Meeting minutes.pdf
2017-12-13 Meeting agenda.pdf
2017-04-27 Meeting minutes.pdf
Privacy policy.pdf
Safeguarding policy.pdf
Welfare policy.pdf

Depending on the formats of the filenames in your directory, you may have to add some more robust parsing.

Tags:

C#

Linq