Sorting months in a list

后端 未结 8 2018
闹比i
闹比i 2020-12-19 10:00

I have a list of strings which contains months of the year. I need to be able to sort this list so the months are in order by month, not alphabetically. I have been search

相关标签:
8条回答
  • 2020-12-19 10:28

    You could parse the string into a DateTime and then sort using the month integer property. See here for supported month names: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx

    Something like this:

    var sortedMonths = monthList
        .Select(x => new { Name = x, Sort = DateTime.ParseExact(x, "MMMM", CultureInfo.InvariantCulture) })
        .OrderBy(x => x.Sort.Month)
        .Select(x => x.Name)
        .ToArray();
    
    0 讨论(0)
  • 2020-12-19 10:29

    You can parse month names into dates (it assumes the current year and day 1):

    monthList = monthList.OrderBy(s=> DateTime.ParseExact(s, "MMMM", new CultureInfo("en-US"))).ToList();
    
    0 讨论(0)
  • 2020-12-19 10:32

    If you insist on having a list of only strings representing months, then you must use another data source to retrieve the index of that month by which you can sort the list. For example, you could populate a dictionary with the month names as string keys and an int index as the value. You can then use the overloaded method List<T>.Sort(Comparison<T>) and pass in a comparison function that returns the index of the months by name (by passing them into the dictionary).

    However, I would recommend not using a raw string in the first place, but rather a more structured data type representing a month. You can then embed the index in the data structure itself and sort based on that value, thus giving you a more self-contained solution.

    0 讨论(0)
  • 2020-12-19 10:33

    You need a SortedList<> .. such as

    SortedList<int,string> monthList=new SortedList<int,string>();
    monthList.Add(6,"June");
    monthList.Add(2,"February");
    monthList.Add(8,"August");   
    IList<string> sortedMonthList=monthList.Values;
    

    then use sortedMonthList for the rest.

    This could be improved by using seldon's answer to create a function, just like

    public static int MonthNumFromName(String monthname)
    { ... }
    

    and then use

    monthList.Add(MonthNumFromName("June"),"June");
    

    above.

    0 讨论(0)
  • 2020-12-19 10:33

    You can build your own sort class:

        static void Main(string[] args)
        {
            List<string> monthList = new List<string>();
            monthList.Add("June");
            monthList.Add("February");
            monthList.Add("August");
    
            monthList.Sort(new _mysort());
    
        }
    
        private class _mysort : IComparer<string>
        {
    
            public int Compare(string x, string y)
            {
                if (x=="February" && y=="June")
                {
                    return -1;
                }
    
                return 0;
            }
        }
    

    But i think you should use an Enum, and convert it to string, then you can use the numeric to sort it.

     enum months
        {
            Jan =0,
            Feb =1
        }
    

    like:

           List<months> mlist = new List<months>() { months.Feb, months.Jan };
            //sort
            mlist = mlist.OrderBy(e => (int)e).ToList();
           //print
            mlist.ForEach(e => Console.WriteLine(e.ToString()));
    
    0 讨论(0)
  • 2020-12-19 10:38

    Well, I guess there aren't any sorting techniques for this with just pure month as string.

    You can just use a Dictionary<int, string> and use the int to sort your months.

    If I haven't mistaken, you are actually having a List of months as string, then why don't you do this?

    List<string> months = new List<string> { "January", "February", ..., "December" };
    
    var yourSortedMonthsInYourOriginalList = months.Where(m => 
                                                  originalList.Any(o => o == m)).ToList();
    
    0 讨论(0)
提交回复
热议问题