2013-02-12 47 views
2

我想通過在可空的Int32字段上使用LINQ的OrderBy方法來對Enumerable<DataRow>類型的集合進行排序。由於此字段的某些值爲空,因此Visual Studio會通過消息「Object必須是Int32類型」引發System.ArgumentException。這是有問題的代碼行:LINQ - 在可空字段上使用OrderBy進行排序

collection1 = collection1.OrderBy(row => row["Column1"]); 

,其中列1是空Int32字段和可變collection1聲明爲:

IEnumerable<DataRow> collection1; 

是否有辦法把上面的線,使得它忽略空值?

回答

4

試試這個:

collection1.OrderBy(row => row.Field<int?>("Column1")); 
+0

感謝哈姆雷特。這工作! – 2013-02-12 12:43:32

0

嘗試以下操作:

collection1 = collection1.Where(row => row["Column1"] != null). 
    OrderBy(row => row["Column1"]); 
7

你可以使用三元條件運算符:

collection1 = collection1.OrderBy(row => 
    row["Column1"] != null ? row["Column1"] : low_priority_indicator); 

哪裏low_priority_indicator是代表一個標準,低順序(對於您的優先級)的整數值。 。否則,如果您想完全從結果集合中排除,則可以在之前過濾掉null

0

這將忽略值 - 試試這個:

collection1 = collection1 
       .Where(c => c["Column1"].HasValue) 
       .OrderBy(row => row["Column1"]);