簡體   English   中英

在列表中排序月份和年份

[英]Sorting months and years in a list

我有一個字符串列表,其中每個字符串都是一個月+年。 我在這里找到了類似的問題但僅列出了幾個月。 所以我的清單看起來像

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

確保將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();

這是我建造的。 它像一種魅力。 有關輸出示例,請參見圖像。 月份和年份下拉列表

 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(); 
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM