Sort an array of objects by date
Given the class below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class MyClass { public int id; public DateTime datetime; public string data; public int MethodX { get { throw new NotImplementedException("Not implemented"); } } } |
Create the array of objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | List<MyClass> items = new List<MyClass>(); for (int i = 1; i <= 100; i++) { int minuteofday = GetRandomNumber(0, 1440); int secondsofday = minuteofday * 60; DateTime d = DateTime.Now.Date.AddSeconds(secondsofday); MyClassitem = new MyClass(); item.datetime = d; items.Add(item); } MyClass[] arrayItems = items.ToArray(); |
Sort the array by the date:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Array.Sort<MyClass>(arrayItems, delegate(item1, item2) { if ((item1== null) && (item2== null)) { // both null, they are equal return 0; } else if ((item1!= null) && (item2== null)) { // first not null, second is return 1; } else if ((item1== null) && (item2!= null)) { // first is null, second is not return -1; } else { return item1.datetime.CompareTo(item2.datetime); } }); |