在列表中对月份和年份进行排序

时间:2014-09-06 13:03:55

标签: c# list sorting date

我有一个字符串列表,其中每个字符串是一个月+年。我发现了类似的问题here,但它只列出了几个月。所以我的列表看起来像那样

List<string> monthsList = new List<string>();
       monthsList.Add("August 2015");
       monthsList.Add("June 2014");
       monthsList.Add("February 2014");
       monthsList.Add("June 2015");

有没有办法像那样订购?

February 2014
June 2014
June 2015
August 2015

2 个答案:

答案 0 :(得分:8)

请确保将DateTime.Parse格式更改为除月份之外的年份:

DateTime.ParseExact(x, "MMMM yyyy", CultureInfo.InvariantCulture)

然后确保更改OrderBy键选择器,使其考虑整个日期,而不仅仅是执行排序的月份:

.OrderBy(x => x.Sort)

完整的代码如下所示:

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

答案 1 :(得分:0)

这是我建造的。它像一种魅力。有关输出示例,请参见图像。 Month and Year Drop Down

 public class MonthAndYear 
    {        
        private string _monthAndYear;

        public string Month { get; set; }
        public IDictionary<string, int> Months { get; set; }
        public int Year { get; set; }
        public string MonthYear
        {
            get
            {
                return string.Concat(Month," ", Year);
            }
            set
            {
                _monthAndYear = value;
            }
        }

        public MonthAndYear()
        {
            Months = new Dictionary<string, int>();
            Months.Add("January", 1);
            Months.Add("February", 2);
            Months.Add("March", 3);
            Months.Add("April", 4);
            Months.Add("May", 5);
            Months.Add("June", 6);
            Months.Add("July", 7);
            Months.Add("August", 8);
            Months.Add("September", 9);
            Months.Add("October", 10);
            Months.Add("November", 11);
            Months.Add("December", 12);
        }        

        public int MonthInteger(string month)
        {
            if (Months.ContainsKey(month))
            {
                return Months[month];
            }
            else
                return 1;
        }

        public List<MonthAndYear> SortMonthAndYear(List<string> _monthYearList)
        {           
            List<MonthAndYear> _sortedMonthAndYear = new List<MonthAndYear>();

            foreach (var _monthYear in _monthYearList)
            {
                _sortedMonthAndYear.Add
                (
                    new MonthAndYear
                    {
                        Month = _monthYear.Substring(0, _monthYear.IndexOf(' ')),
                        Year = Convert.ToInt32(_monthYear.Substring(Math.Max(0, _monthYear.Length - 4)))
                    }
                );
            }            
            return _sortedMonthAndYear.OrderBy(y => y.Year).ThenBy(m => m.MonthInteger(m.Month)).ToList(); 
        }

    }