简体   繁体   中英

C# Sort array element in list by date

I have a list

List<string[]> myList = new List<string[]>();

that holds an array that I want to sort by date inside of the list.

string[] myArray = new string[3];

The date is saved in place 0 in the array.

myArray[0] = (Convert.ToDateTime(Console.ReadLine())).ToString("yyyy/MM/dd");

How is that possible, when my print code looks like this?

foreach (string[] element in myList) {
   Console.WriteLine("{0} {1} {2}", element[0], element[1], element[2]);
}

You can use List.Sort and DateTime.ParseExact :

myList.Sort((arr1, arr2) => DateTime.ParseExact(arr1[0], "yyyy'/'MM'/'dd", null)
                 .CompareTo(DateTime.ParseExact(arr2[0], "yyyy'/'MM'/'dd", null)));

This presumes that all have a valid format, otherwise you'll get an exception.

Instead of accessing data from an arbitrary array of strings, you should construct an object that represents your data and then make your list a list of this class.

public class MyObject
{
    public DateTime Date {get;set;}
    public string Param2  {get;set;}
    public string Param3  {get;set;}
}
List<MyObject> myList = new List<MyObject>();

In which case the sorting becomes trivial

foreach (var element in myList.OrderBy(x => x.Date))

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