执行左外连接

时间:2019-05-31 10:56:31

标签: c# linq

我有两个对象列表,想要执行左外部联接。

此代码不会返回ds.partNumber不等于ctd.partNumber且记录值为空的记录:

partClass = ds.partClass
componentState = ds.componentState

var query = from ds in DS2recordsList
            join ctd in recordsList
            on ds.partNumber equals ctd.partNumber 
            select new
            {
                ID = ctd.ID,
                type = ctd.type,
                status = ctd.status,
                partNumber = ctd.partNumber,
                requestDate = ctd.requestDate,
                completionDate = ctd.completionDate,
                expectedComplitionDate = ctd.expectedComplitionDate,
                startPendingDate = ctd.startPendingDate,
                endPendingDate = ctd.endPendingDate,
                sentToCEP = ctd.sentToCEP,
                gotFromCEP = ctd.gotFromCEP,
                partClass = ds.partClass,
                componentState = ds.componentState
            };

```

我从https://docs.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins那里得到了这个例子
以下示例无法编译:

    var query = from ctd in recordsList
                            join ds in DS2recordsList
                            on ctd.partNumber equals ds.partNumber
                            into a
                            from b in a.DefaultIfEmpty()
                            select new
                            {
                                ID = ctd.ID,
                                type = ctd.type,
                                status = ctd.status,
                                partNumber = ctd.partNumber,
                                requestDate = ctd.requestDate,
                                completionDate = ctd.completionDate,
                                expectedComplitionDate = ctd.expectedComplitionDate,
                                startPendingDate = ctd.startPendingDate,
                                endPendingDate = ctd.endPendingDate,
                                sentToCEP = ctd.sentToCEP,
                                gotFromCEP = ctd.gotFromCEP,
                                partClass = b?.partClass ?? String.Empty,
                                componentState = b?.componentState ?? String.Empty 

                            };

如果我使用这个:

partClass = b.partClass,
componentState = b.componentState 

它抛出以下异常:

  

类型为'System.NullReferenceException'的未处理异常   发生在Statistics.exe

0 个答案:

没有答案