Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ的左外联接列选择_C#_Linq - Fatal编程技术网

C# LINQ的左外联接列选择

C# LINQ的左外联接列选择,c#,linq,C#,Linq,我有三个数据集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["Subscri

我有三个数据集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中的左连接不返回其他非空值?有没有办法避免这种情况

我这样问是因为我的代码需要继续与其他表(如-

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


在更大的查询中,仍然需要处理b为null的可能性。你真的想在这里使用左外连接,而不是LINQ join子句提供的内部连接吗?

哦,我可怜的眼睛:请使用代码格式选项格式化代码编辑器中的小二进制按钮format complete,我今天做的好事。这很有趣。四个人同时编辑这个问题。大卫,谢谢!我尝试了几次格式化,但还是搞砸了。马特,谢谢!我现在学习代码格式化选项。下次我会做的。罗伯特,很酷的编辑。酷偶像,酷乔恩。这就是我需要知道的。我现在想要一个左外连接。顺便说一句,你的C深度是我最喜欢的书之一。我用硬拷贝和电子拷贝读了两遍。希望你发表更多。