我有 1 個主表和 3 個用于對主表中的欄位進行排序的表。我將所有這些表作為串列回傳。
主表結構是這樣的:
| 顏色 | 制作 | 國家 |
|---|---|---|
| 黑色的 | 梅賽德斯 | 德國 |
| 藍色 | 梅賽德斯 | 德國 |
| 青色 | 梅賽德斯 | 德國 |
| 紅色的 | 梅賽德斯 | 德國 |
| 藍色 | 寶馬 | 德國 |
| 紅色的 | 寶馬 | 德國 |
| 藍色 | 豐田 | 日本 |
| 紫色的 | 梅賽德斯 | 德國 |
并且訂購表在主表中有欄位名稱和另一個用于訂購編號的數字欄位,例如:
| 顏色 | 色階 |
|---|---|
| 黑色的 | 6 |
| 藍色 | 2 |
| 青色 | 3 |
| 紅色的 | 4 |
現在我想根據 Linq 中的訂購表中的訂購號對主表進行訂購。如果在主表上,如果訂購表中沒有相應的欄位,則訂購號應為 0(例如在 ColorOrdering 中沒有紫色)
具體來說,我在 Access 和 Query 中制作了一個作業示例,如下所示:
SELECT Cars.Color, Cars.Make, Cars.Country,
IIf([MakeOrder] Is Null,0,[MakeOrder]) AS MkOrder,
IIf([ColorOrder] Is Null,0,[ColorOrder]) AS ClOrder,
IIf([CountryOrder] Is Null,0,[CountryOrder]) AS CntOrder
FROM ((Cars LEFT JOIN ColorOrder ON Cars.Color = ColorOrder.Color)
LEFT JOIN MakeOrder ON Cars.Make = MakeOrder.Make)
LEFT JOIN CountryOrder ON Cars.Country = CountryOrder.Country
ORDER BY
IIf([MakeOrder] Is Null,0,[MakeOrder]),
IIf([ColorOrder] Is Null,0,[ColorOrder]),
IIf([CountryOrder] Is Null,0,[CountryOrder]);
我的問題是其中一個排序表沒有記錄(國家/地區表)。所以當我加入那張桌子時,無論我做什么,我都會得到,
System.NullReferenceException: 'Object reference not set to an instance of an object.' cntord was null.
Here is my Linq Query, help on this is much appreciated
List<CarsWithOrdering> carsWithOrdering = (from c in Cars
//Also tried this, doesn't work
//join cntord in CountryOrderingList.DefaultIfEmpty()
// on c.Country equals cntord.Country
join cntord in CountryOrderingList
on c.Country equals cntord.Country into lcntord
from cntord in lcntord.DefaultIfEmpty()
//........ (Other 2 left joins similar to above one)
select new CarsWithOrdering
{
Color = c.Color,
Make = c.Make,
Country = c.Country,
ColorOrder = int.Parse(colord.ItemValue) ?? 0,
MakeOrder = int.Parse(makord.ItemValue) ?? 0,
CountryOrder = int.Parse(cntord.ItemValue) ?? 0
}).ToList();
uj5u.com熱心網友回復:
Enumerable.DefaultIfEmpty 方法
public static System.Collections.Generic.IEnumerable<TSource> DefaultIfEmpty<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue);
退貨
IEnumerable 如果源為空,則包含 defaultValue 的 IEnumerable;否則,來源。
.DefaultIfEmpty()null當串列為空時將回傳。
解決方案
因此,您需要null在訪問其屬性之前檢查LEFT JOIN 表的值。
List<CarsWithOrdering> carsWithOrdering = (from c in Cars
join cntord in CountryOrderingList
on c.Country equals cntord.Country into lcntord
from cntord in lcntord.DefaultIfEmpty()
//Other LEFT JOIN tables
select new CarsWithOrdering
{
Color = c.Color,
Make = c.Make,
Country = c.Country,
ColorOrder = colord != null ? int.Parse(colord.ItemValue) : 0,
MakeOrder = makord != null ? int.Parse(makord.ItemValue) : 0,
CountryOrder = cntord != null ? int.Parse(cntord.ItemValue) : 0
})
.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352930.html
上一篇:將XDocument.Descendants與合并運算子一起使用??和可空型別
下一篇:根據另一個串列條件過濾串列
