简体   繁体   中英

Sort a list of dates entered by user in ascending order

Sort a list of dates in ascending order given the data format shown below: Each date is in the form dd mmm yyyy where: dd is in the set {0-31} mmm is in the set {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} yyyy is four digits Example dates = ['01 Mar 2017','03 Feb 2017','15 Jan 1998'] The array dates sorts to to ['15 Jan 1998' '03 Feb 2017' '01 Mar 2017']

Function Description: Complete the function sortDates in the editor below. sortDates has the following parameter: string dates[n]: an array of strings, each field separated by a space Returns: string arr[n]: The function must return an array of date strings sorted chronologically ascending

Constraints 2≤lengthofdates≤30

Thank Please complete the sortdates function:

Class Results{ Public static List SortDates(List dates) }

Here is the solution

using System;
using System.Collections.Generic;
using System.Linq;

namespace Results
{
    class Program
    {
        static void Main(string[] args)
        {
            var dates = new string[] { "01 Mar 2017", "03 Feb 2017", "15 Jan 1998" };
            var sortedDates =SortDate(dates);
            Console.WriteLine(String.Join(',', sortedDates));
        }

        private static IEnumerable<string> SortDate(string[] dates)
        {
            return dates.Select(x => Convert.ToDateTime(x)).OrderBy(y => y)
                .Select(z => z.ToString("dd MMM yyyy"));
        }
    }
}

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