0

我正在尝试在 linq 中对一个列表进行左外连接,因此如果我有一个带有 {1,2,3,4} 的列表和另一个带有 {1,2,3,5} 的列表,我想要 { 4}。

在此处输入图像描述

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);
            }
        }

当我运行这段代码时,我得到了这个异常:

测试方法 Tgw.Systems.Alerting.Server.Test.ConfigurationTests.UpdateCacheWith2recordsSameIdWorking 抛出异常:System.NullReferenceException:对象引用未设置为对象的实例。在 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__313.MoveNext() 在 Tgw.Wcs.Alerting.MonitoringAddIn.Oms.Wcf.OmsWcfSystemMonitor.UpdateAlertsFromCache(IList`1 loadedAlerts) 在 OmsWcfSystemMonitor。 cs:ConfigurationTests.ServerCoreTests.cs 中 Tgw.Systems.Alerting.Server.Test.ConfigurationTests.UpdateCacheWith2recordsSameIdWorking() 的第 275 行:第 243 行

我认为问题是Guid!

4

1 回答 1

2

尝试

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

因为 b 可以是null您无法将其与 Guid.Empty 进行比较

??是空合并运算符。这意味着该语句将使用第一个非空值进行赋值。

//编辑

你说的对。我没有测试它。

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

这在这里应该工作。Guid 是一个特例,因为它在设计上不能为空。

于 2012-12-18T13:32:05.610 回答