[英]Left outer join with null LINQ exception with Guids
我試圖在一個List的linq中使用null進行左外連接,所以如果我有一個列表{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:未將對象引用設置為對象的實例。 在OmsWcfSystemMonitor.cs中的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( )位於OmsWcfSystemMonitor.cs中的Tgw.Wcs.Alerting.MonitoringAddIn.Oms.Wcf.OmsWcfSystemMonitor.UpdateAlertsFromCache(IList`1 loadedAlerts):位於275的ConfigurationTests.ServerCoreTests中的Tgw.Systems.Alerting.Server.Test.ConfigurationTests.UpdateCacheWith2recordsSameIdWorking() .cs:第243行
我認為問題是Guid!
嘗試
AlertId = b.AlertId ?? a.AlertId ?? Guid.Empty;
因為b可以為null
,所以無法將其與Guid.Empty進行比較
??
是空合並運算符。 這意味着該語句將使用第一個非null值進行賦值。
// 編輯 :
你是對的。 我沒有測試它。
AlertId = ( b == null ) ? a.AlertId : Guid.Empty;
這應該工作。 Guid是一個特例,因為它不能被設計為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.