2012-12-18 31 views
0

我想做一個左空外部連接與列表中的linq空,所以如果我有一個列表{1,2,3,4}和其他與{1 ,2,3,5},我想要{4}。左外部連接與空LINQ異常與Guids

enter image description here

IEnumerable<AlertChangeSet> listToClear = from a in AlertsCached 
                join b in loadedAlerts on a.AlertId equals b.AlertId into c 
                from b in c.DefaultIfEmpty() 
                select new AlertChangeSet() 
                 { 
                  AlertId = b.AlertId == Guid.Empty ? a.AlertId : Guid.Empty 

                 }; 
    if (listToClear.Any()) 
     { 
      foreach (AlertChangeSet alertChangeSet in listToClear) 
      { 
       Guid a = alertChangeSet.AlertId; 
       //SystemMonitoringService.ClearAlertAsync(alertChangeSet.AlertId.ToString(), null); 
      } 
     } 

當我運行這段代碼,我得到這個異常:

Test method Tgw.Systems.Alerting.Server.Test.ConfigurationTests.UpdateCacheWith2recordsSameIdWorking threw exception: System.NullReferenceException: Object reference not set to an instance of an object. at Tgw.Wcs.Alerting.MonitoringAddIn.Oms.Wcf.OmsWcfSystemMonitor.b__c(<>f__AnonymousType0 2 <>h__TransparentIdentifier2, AlertChangeSet b) in OmsWcfSystemMonitor.cs: line 255 at System.Linq.Enumerable.<SelectManyIterator>d__31 3.MoveNext() at Tgw.Wcs.Alerting.MonitoringAddIn.Oms.Wcf.OmsWcfSystemMonitor.UpdateAlertsFromCache(IList`1 loadedAlerts) in OmsWcfSystemMonitor.cs: line 275 at Tgw.Systems.Alerting.Server.Test.ConfigurationTests.UpdateCacheWith2recordsSameIdWorking() in ConfigurationTests.ServerCoreTests.cs: line 243

我認爲這個問題是的GUID!

回答

2

嘗試

AlertId = b.AlertId ?? a.AlertId ?? Guid.Empty; 

因爲B可以是null你不能把它比作Guid.Empty

??是空合併運算符。這意味着該語句將爲該分配使用第一個非空值。

// 編輯

你是對的。我沒有測試它。

AlertId = (b == null) ? a.AlertId : Guid.Empty; 

這裏應該工作。 Guid是一個特例,因爲它不能被設計爲空。

+1

Guid不能爲空,不能轉換爲Guid?所以我得到一個編譯錯誤:「運營商」??不能應用於'System.Guid'類型的操作數「 –