2012-12-18 30 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'类型的操作数“ –