如何从列表中的列中选择Nullable Value

时间:2013-07-01 06:31:11

标签: c# linq linq-to-dataset

如何从列表中的列中选择Nullable Value。

比如说我将数据集转换为如下所示的列表,而不是在客户端ID(可空列)中传递值。我需要传递null。我自己做了以下尝试:

var reqlist = (from list in tableList.AsEnumerable()
                where (list.Field<int?>("ClientID") == clientID)
                       && list.Field<bool>("VisibleToAdmin") == true
                       && list.Field<bool>("Required") == true
                select list.Field<string>("FieldName"));

1

var reqlist = (from list in tableList.AsEnumerable()
                 where (list.Field<int?>("ClientID") == null)
                        && list.Field<bool>("VisibleToAdmin") == true
                        && list.Field<bool>("Required") == true
                 select list.Field<string>("FieldName"));

2

var reqlist = (from list in tableList.AsEnumerable()
                 where (list.Field<int?>("ClientID") == (int?)(null))
                        && list.Field<bool>("VisibleToAdmin") == true
                        && list.Field<bool>("Required") == true
                 select list.Field<string>("FieldName"));

3

var reqlist = (from list in tableList.AsEnumerable()
                 where (list.Field<int?>("ClientID") == (bool?)(null))
                        && list.Field<bool>("VisibleToAdmin") == true
                        && list.Field<bool>("Required") == true
                 select list.Field<string>("FieldName"));

4

var reqlist = (from list in tableList.AsEnumerable()
                 where (list.IsNull("ClientID"))
                        && list.Field<bool>("VisibleToAdmin") == true
                        && list.Field<bool>("Required") == true
                 select list.Field<string>("FieldName"));

使用上述所有方法,都会抛出InvalidCastException

1 个答案:

答案 0 :(得分:0)

将可空值与null进行比较是完全合法的:

list.Field<int?>("ClientID") == null
// same as 
!list.Field<int?>("ClientID").HasValue

您似乎在 VisibleToAdmin 必需字段中有DbNull.Value。因此,您应该使用可空的bool来获取这些字段值:

int? clientID = null;
var reqlist = from r in tableList.AsEnumerable()
              where r.Field<int?>("ClientID") == clientID &&
                    r.Field<bool?>("VisibleToAdmin") == true &&
                    r.Field<bool?>("Required") == true
              select r.Field<string>("FieldName");