Sorting a list of IComparables I have a DateTime class (my own, not System.DateTime) which implements the IComparable interface.

Here is a method that takes a List&lt;DateTime&gt; and sorts it:

private List&lt;DateTime&gt; SortDateTimes(List&lt;DateTime&gt; dateTimes)
{
    for (int i = 0; i &lt; dateTimes.Count; i++)
    {
        for (int j = 0; j &lt; dateTimes.Count; j++)
        {
            if (dateTimes[i] &lt; 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!
Prologue


  I have a DateTime class (my own, not System.DateTime)


You could have just pasted the code for that class. Since you are asking a question about sorting, and your DateTime class implements IComparable, its content could have been pivotal for a proper review.

Parodos


  Here is a method that takes a List&lt;DateTime&gt; and sorts it:


You have just told us your class implements IComparable, but you don't show us how you'd use its functionality. I would have expected to to see dateTimes[i].CompareTo(dateTimes[j]) but instead we get dateTimes[i] &lt; dateTimes[j]. This means you have created an operator overload on &lt; and are not sharing this crucial code with us.

Furthermore, why would you roll out your own sorting algorithm if built-in functionality is available? As suggested in the comments by VisualMelon, you could just call dateTimes.Sort();

Exodus


  I believe using foreach loops instead of for is suitable here, but having the following variable names drives me crazy


To get things even more confusing, you ask about a syntactic change to the algorithm rather than going about how to properly sort or how to correctly implement IComparable.

Finishing off, in the for (dateTime1 in dateTimes) approach, you cannot change dateTimes[i] = dateTimes[j]; as it will throw System.InvalidOperationException: Collection was modified; enumeration operation may not execute. rendering your suggested approach unusable. 

Cliffhanger

As a challenge, I let you search how to prevent this exception.