title: Sorting objects in ArrayList by DateTime variable inside the objects
body: <p>I have a problem.</p>
  
  <p>I have an <code>ArrayList</code> of objects. Each object contains a <code>DateTime</code> data field.</p>
  
  <p>I need to sort this <code>ArrayList</code> by this <code>DateTime</code> data field.</p>
  
  <p>This is my current code and it does not work:</p>
  
  <pre><code>        for (int i = 0;i&lt;EventHolder.Count;i++)
          {
              Event obj = (Event) EventHolder[i];
              try
              {
                  obj2=(Event)EventHolder[i+1];
              }
              catch
              {
                  break;
              }
              DateTime date1 = DateTime.ParseExact(obj.Date_And_Time,"dd/MM/yyyy HH:mm",region);
              DateTime date2 = DateTime.ParseExact(obj2.Date_And_Time, "dd/MM/yyyy HH:mm", region);
              if (DateTime.Compare(date1,date2)&gt;0)
              {
                  Event tempobj=obj2;
                  EventHolder[i+1]=obj;
                  EventHolder[i]=tempobj;
              }
          }
          foreach (Event i in EventHolder)
          {
              Console.WriteLine(i.Date_And_Time);
          }
          Console.ReadLine();
  </code></pre>
  
  <p>I use these 3 dates to test if it works:</p>
  
  <blockquote>
    <p>23/11/2011 12:15</p>
    
    <p>28/06/2010 04:05</p>
    
    <p>02/09/1992 03:54</p>
  </blockquote>
  
  <p>The output is always:</p>
  
  <blockquote>
    <p>28/06/2010 04:05</p>
    
    <p>02/09/1992 03:54</p>
    
    <p>23/11/2011 12:15</p>
  </blockquote>
  
  <p>I tried using just > and &lt; operators for comparing and got same results. I also tried using different commands to convert the strings to DateTime objects, like <code>Convert.ToDateTime</code>, <code>DateTime.Parse</code>. Tried entering without HH:mm (adjusted the code accordingly) and still had the same output. I tried not using <code>IFormatProvider</code> (set it to null) and got nowhere again.</p>
  
  <p>By chance, I found this thread: </p>
  
  <p><a href="https://stackoverflow.com/questions/844251/how-to-sort-arraylist-of-datetime-objects-in-descending-order">How to sort ArrayList of DateTime objects in descending order?</a></p>
  
  <p>I extracted all the dates from the objects and put them into this DateTime list. Used <code>List.Sort()</code> and it produced correct output. But then I got stuck at how to use this sorted list to sort my EventHolder ArrayList. I've been banging on this wall for a while, and produced no result.</p>
  
  <p>I am very new to programming, so I hardly know any good way of doing what I'm doing. And it doesn't even work.
  Can anybody explain to me where I'm going wrong?</p>