2016-04-22 107 views
0

我有一個數據集,我正在做一個linq查詢。檢查Linq查詢中的空值

var results = dtWorkCenters.AsEnumerable() 
      .Where(x => x.Field<string>("Work_Center") == theWorkCenter && x.Field<string>("Job") == theJob) 
      .Select(x => new 
       { 
        Operation = x.Field<string>("Job_Operation"), 
        WorkDate = x.Field<DateTime>("Work_Date"), 
        Employee = x.Field<string>("Employee"), 
        SetupHours = x.Field<double>("Act_Setup_Hrs"), 
        SetupDollars = x.Field<double>("Act_Labor_Dollars"), 
        RunHours = x.Field<double>("Act_Run_Hrs"), 
        RunDollars = x.Field<double>("Act_Labor_Dollars") 
       }); 

該字段Job_Operation是一個字符串int數據庫,但可能包含一個空值。上述語法在空值上失敗。我如何防範數據中的空值?

+1

你確定你的問題是'string'領域?因爲'string'可以包含'null'值,但是'DateTime'和'double'不能。 –

+0

是的,我可以從查詢中刪除字符串字段,它運行良好。 –

回答

1

我覺得你與null值遇到的問題可能是試圖將值類型(DateTimedouble)性能(WorkDateSetupHours等)設置爲null結果。

如果是這樣的情況下,嘗試通過使用您的通話DateTime?double?指定Nullable<DateTime>Nullable<double>作爲通用Field類型x.Field<T>像這樣:

var results = dtWorkCenters.AsEnumerable() 
        .Where(x => x.Field<string>("Work_Center") == theWorkCenter 
            && x.Field<string>("Job") == theJob) 
        .Select(x => new 
           { 
            Operation = x.Field<string>("Job_Operation"), 
            WorkDate = x.Field<DateTime?>("Work_Date"), 
            Employee = x.Field<string>("Employee"), 
            SetupHours = x.Field<double?>("Act_Setup_Hrs"), 
            SetupDollars = x.Field<double?>("Act_Labor_Dollars"), 
            RunHours = x.Field<double?>("Act_Run_Hrs"), 
            RunDollars = x.Field<double?>("Act_Labor_Dollars") 
           });