简体   繁体   中英

sorting months and years in a c# list

I have a list of strings where each string is a month and year

List<string> Dates = new List<string>
{
     "DEC16",
     "SEP16",
     "JUN16",
     "MAR15"
};

any way to order it like this

"MAR15",
"JUN16",
"SEP16",
"DEC16"

You can:

List<string> Dates = new List<string> {
    "DEC16",
    "SEP16",
    "JUN16",
    "MAR15"
};

Dates.Sort((p, q) => 
    DateTime.ParseExact(p, "MMMyy", CultureInfo.InvariantCulture).CompareTo(
    DateTime.ParseExact(q, "MMMyy", CultureInfo.InvariantCulture)));

This because with the DateTime.ParseExact you can actually parse those dates (they will be converted to 1 December 2016 00:00 and so on)

Note that the months must be JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC (upper or lowercase)

var sortedMonths = Dates
        .Select(x => new {
            Name = x,
            Sort = DateTime.ParseExact(x, "MMMyy", CultureInfo.InvariantCulture)
        })
        .OrderBy(x => x.Sort)
        .Select(x => x.Name)
        .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM