我有一個用戶控件,因爲網格使用ObjectDataSource獲取數據。網格中的所有列都是可排序的。如果用戶點擊某個特定的列名稱,該列表將根據該列(List.Sort(sortColumn))進行排序。List.Sort()在列表中有空值時失敗
我正面臨一個問題,其中一列的空白/空值在他們的領域。當strA/strB爲空或兩者都爲空時,比較行strA.CompareTo(strB)會失敗,並且「對象引用未設置爲對象的實例」。
如何,我已經包括!string.IsNullOrEmpty()爲strA和strB,以避免空引用異常。它仍然不排序網格。
下面給出了代碼片段。
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;
}
如何對其中一個值或兩者都爲空進行排序。
注:我使用VS 2005,所以LINQ雖然沒有可能。
請建議。
感謝, 斯利拉姆
我沒有爲你解決,但你只需要聲明一個PropertyInfo對象,因爲這兩個項目都是同一類。您可以使用該PropertyInfo對象在兩個項目上調用.GetValue。由於處理器的反射比較「昂貴」,所以這只是一個小小的性能提升。 – MCattle 2012-04-23 14:42:12