My C# ListView Compare Function is too slow
<p>I am trying to sort a <code>ListView</code> which also has a <code>DateTime</code> column. This is the code I use:</p>

<pre><code>public bool isDate(Object obj)
{
    string strDate = obj.ToString();
    try
    {
        DateTime dt = DateTime.Parse(strDate);
        if (dt != DateTime.MinValue &amp;&amp; dt != DateTime.MaxValue)
            return true;
        return false;
    }
    catch
    {
        return false;
    }
}

public int Compare(object o1, object o2)
{
    if (!(o1 is ListViewItem))
        return (0);
    if (!(o2 is ListViewItem))
        return (0);

    ListViewItem lvi1 = (ListViewItem)o2;
    string str1 = lvi1.SubItems[ByColumn].Text;
    ListViewItem lvi2 = (ListViewItem)o1;
    string str2 = lvi2.SubItems[ByColumn].Text;

    int result;
    if (lvi1.ListView.Sorting == SortOrder.Ascending)
    {
        if (isDate(str1) &amp;&amp; isDate(str2))
            result = DateTime.Compare(DateTime.Parse(str1), DateTime.Parse(str2));
        else
            result = String.Compare(str1, str2);
    }
    else
        result = String.Compare(str2, str1);

    LastSort = ByColumn;
    return result;
}
</code></pre>

<p>The <code>ListView</code> holds about 2000 entries and the problem is that it's very slow. What am I doing wrong? Any ideas?</p>

<p>Thanks in advance!</p>

<p><strong>Edit:</strong> Thank you very much. I am new to this and here is my code now. It is much faster and I fixed my logic.</p>

<pre><code>public int Compare(object o1, object o2)
{
    var lvi1 = o2 as ListViewItem;
    var lvi2 = o1 as ListViewItem;
    if (lvi1 == null || lvi2 == null)
        return 0;

    string str1 = lvi1.SubItems[ByColumn].Text;
    string str2 = lvi2.SubItems[ByColumn].Text;

    int result;
    DateTime dateValue1 = new DateTime();
    DateTime dateValue2 = new DateTime();

    if (lvi1.ListView.Sorting == SortOrder.Ascending)
    {  
        if (DateTime.TryParse(str1, out dateValue1) &amp;&amp; DateTime.TryParse(str2, out dateValue2)) 
            result = DateTime.Compare(dateValue1, dateValue2);
        else
            result = String.Compare(str1, str2);
    }
    else
    {
        if (DateTime.TryParse(str1, out dateValue1) &amp;&amp; DateTime.TryParse(str2, out dateValue2))
            result = DateTime.Compare(dateValue2, dateValue1);
        else
            result = String.Compare(str2, str1);
    }

    LastSort = ByColumn;
    return result;  
}
</code></pre>
