gpt4 book ai didi

c# - LINQ的Left outer join列选择

转载 作者:行者123 更新时间:2023-11-30 16:33:19 25 4
gpt4 key购买 nike

我有数据集 ds 中的三个表。

var test0 = from a in ds.Tables[0].AsEnumerable()
select a["ID"].ToString();

test0 具有以下值 --

  [0] "8" 
[1] "9"
[2] "11"
[3] "2"
[4] "1"

var test1 = from a in ds.Tables[1].AsEnumerable()
select a["SubscriptionID"].ToString();

test1 有这些——

  [0] "25" 
[1] "27"
[2] "4"
[3] "26"
[4] "5"
[5] "6"
[6] "1"
[7] "24"
[8] "23"
[9] "2"
[10] "9"

var comTable1 =
from a in ds.Tables[0].AsEnumerable()
from b in ds.Tables[1].AsEnumerable()
.Where(bb => bb["SubscriptionID"].ToString() == a["ID"].ToString())
.DefaultIfEmpty()
select b;

comTable1 返回这些正确的值 --

   [0] null  
[1] {System.Data.DataRow}
[2] null
[3] {System.Data.DataRow}
[4] {System.Data.DataRow}

我的问题是,如果我想选择特定字段,它会抛出一条消息“对象引用未设置为对象的实例”。在 comTable2 中使用以下代码 --

var comTable2 =
from a in ds.Tables[0].AsEnumerable()
from b in ds.Tables[1].AsEnumerable()
.Where(bb => bb["SubscriptionID"].ToString() == a["ID"].ToString())
.DefaultIfEmpty()
select b["SubscriptionID"];

为什么LINQ中的left join不返回其他非空值?有没有办法避免这种情况?

我问这个是因为我的代码需要继续与其他表进行左连接,例如 --

var comTable =
from a in ds.Tables[0].AsEnumerable()
from b in ds.Tables[1].AsEnumerable()
.Where(bb => bb["SubscriptionID"].ToString() == a["ID"].ToString())
.DefaultIfEmpty()
from c in ds.Tables[2].AsEnumerable()
.Where(cc => cc["ID"].ToString() == (b["GroupID"]??"null").ToString())
.DefaultIfEmpty()
select c;

现在我无法从 b 和 c 得到任何东西。

谢谢!

最佳答案

是的 - 如果您尝试取消引用空值,您得到一个异常。试试这个:

var comTable2 = from a in ds.Tables[0].AsEnumerable()
from b in ds.Tables[1]
.AsEnumerable()
.Where(bb => bb["SubscriptionID"].ToString()
== a["ID"].ToString())
.DefaultIfEmpty()
select b == null ? null : b["SubscriptionID"];

基本上,末尾的条件表达式将在没有匹配项的地方留下空值,如果匹配则保留订阅 ID。

在更大的查询中,您仍然需要处理 bnull 的可能性。您绝对想要在此处使用左外连接,而不是 LINQ 连接子句提供的内连接吗?

关于c# - LINQ的Left outer join列选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3365723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com