Sriram B
Sriram B

Reputation: 691

List.Sort() fails when the list has null values

I have a user control in that a grid gets data using ObjectDataSource. All the columns in the grid are sortable. If the user clicks on a particular column name, the list is sorted based on that column (List.Sort(sortColumn)).

I am facing an issue when one of the column has blank / null value in their field. The comparison line strA.CompareTo(strB) fails with "Object reference not set to an instance of an object" when strA/ strB is null or both are null.

How ever, I have included !string.IsNullOrEmpty() for strA and strB to avoid the null refernce exception. Still it doesn't sort the grid.

The code snippet is given below.

int IComparer<MyWorklistItem>.Compare(MyWorkItem x, MyWorkItem y)
{
        int sortValue = 1;
        if (this.strSortField.Length == 0)
        {
            return 0;
        }
        MyWorkItem item1 = this.blnSortDesc ? y : x;
        MyWorkItem item2 = this.blnSortDesc ? x : y;

        PropertyInfo property1 = item1.GetType().GetProperty(this.strSortField);
        PropertyInfo property2 = item2.GetType().GetProperty(this.strSortField);

        string strA = (string)property1.GetValue(item1, null);
        string strB = (string)property2.GetValue(item2, null);

        if (!string.IsNullOrEmpty(strA) && !string.IsNullOrEmpty(strB))
        {               
            sortValue = strA.CompareTo(strB);
        }           
        return sortValue;
    }

How do I sort, when one of the values or both are null.

Note: I am using VS 2005, so no possibility for LINQ though.

Please suggest.

Thanks, Sriram

Upvotes: 3

Views: 809

Answers (2)

Eric J.
Eric J.

Reputation: 150108

You can use the static string.Compare method rather than the instance method to avoid problems with null, given that you are always comparing string properties.

http://msdn.microsoft.com/en-us/library/system.string.compare.aspx

Upvotes: 3

Servy
Servy

Reputation: 203828

You're calling GetType on the variables before doing the null check.

If you do a null check before anything else that should take care of everything.

Upvotes: 0

Related Questions