LINQ - 在可空字段上使用OrderBy进行排序

Yos*_*ete 2 linq

我正在尝试Enumerable<DataRow>通过在可空的Int32字段上使用LINQ的OrderBy方法对类型集合进行排序.由于此字段的某些值为null,因此Visual Studio会抛出System.ArgumentException,并显示消息"Object必须是Int32类型".这是有问题的代码行:

collection1 = collection1.OrderBy(row => row["Column1"]); 
Run Code Online (Sandbox Code Playgroud)

其中Column1是可空的Int32字段,变量collection1声明为:

IEnumerable<DataRow> collection1;
Run Code Online (Sandbox Code Playgroud)

有没有办法重写上面的行,以便它忽略空值?

Gra*_*mas 7

您可以使用三元条件运算符:

collection1 = collection1.OrderBy(row => 
  row["Column1"] != null ? row["Column1"] : low_priority_indicator); 
Run Code Online (Sandbox Code Playgroud)

哪个low_priority_indicator是表示标准,低阶(相对于您的优先级)值的整数.否则,如果要完全从结果集合中排除,则可以排序之前过滤掉null值.