[英]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) 这是因为使用DateTime.ParseExact
实际上可以解析这些日期(它们将转换为1 December 2016 00:00
,依此类推)
Note that the months must be JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC (upper or lowercase) 请注意,月份必须为1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月(大写或小写)
var sortedMonths = Dates
.Select(x => new {
Name = x,
Sort = DateTime.ParseExact(x, "MMMyy", CultureInfo.InvariantCulture)
})
.OrderBy(x => x.Sort)
.Select(x => x.Name)
.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.