I have a DateTime
class (my own, not System.DateTime
) which implements the IComparable
interface.
Here is a method that takes a List<DateTime>
and sorts it:
private List<DateTime> SortDateTimes(List<DateTime> dateTimes)
{
for (int i = 0; i < dateTimes.Count; i++)
{
for (int j = 0; j < dateTimes.Count; j++)
{
if (dateTimes[i] < dateTimes[j])
{
var temp = dateTimes[i];
dateTimes[i] = dateTimes[j];
dateTimes[j] = temp;
}
}
}
return dateTimes;
}
I believe using foreach
loops instead of for
is suitable here, but having the following variable names drives me crazy. :D
foreach(var dateTime1 in dateTimes)
{
foreach(var dateTime2 in datetimes)
...
What are your thoughts? Thanks!
List.Sort
? Here you have provided a something not far off a (comparatively poor, since it lacks a cutoff) bubble sort, which will taken^2
steps to sort your list, wheren
is the number of items in the list. An 'efficient' sorting algorithm (asList.Sort
will use) will do the same job inn log(n)
steps, which is big difference for a largen
. \$\endgroup\$dateTimes.Sort()
? \$\endgroup\$List<T>.Sort
which details how theDefaultComparer<T>
is prepared. As long as you don't try to do anything silly with it, nothing will go wrong, and if you do try to do something silly with it then it will tell you by throwing an exception. \$\endgroup\$DateTime
class something else - just about anything else. Obviously two types can have the same name, but it's not worth even the moment of confusion caused by using the same name as such a common type. \$\endgroup\$