Sort an array of objects by date
Given the class below:
public class MyClass
{
public int id;
public DateTime datetime;
public string data;
public int MethodX
{
get
{
throw new NotImplementedException("Not implemented");
}
}
}
{
public int id;
public DateTime datetime;
public string data;
public int MethodX
{
get
{
throw new NotImplementedException("Not implemented");
}
}
}
Create the array of objects:
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();
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:
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);
}
});
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);
}
});