简体   繁体   中英

Left outer join with null LINQ exception with Guids

I am trying to do a left outer join with null in linq over a List, so if I have one list with {1,2,3,4} and other with {1,2,3,5}, I want the {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);
            }
        }

When I run this code, I get this exception:

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

I think the problem is the Guid!

try

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

because b can be null you cannot compare it to Guid.Empty

?? is the null-coalescing operator. That means that the statement will use the first not-null value for the assignment.

// EDIT :

You are right. I didn't test it.

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

This here should work. Guid was a special case, because it cannot be null by design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM