离开加入Linq?

时间:2010-09-05 22:35:57

标签: c# linq

我实际上不确定这是否恰好是左连接;我不是SQL的专家。我有以下Linq查询:

        var title = dataSet.Tables["title"].AsEnumerable();
        var author = dataSet.Tables["author"].AsEnumerable();
        var review = dataSet.Tables["review"].AsEnumerable();

        var results = from t in title
                      join a in author on t["Url"] equals a["Url"]
                      join r in review on t["Url"] equals r["Url"]
                      select new { 
                          tText = t["InnerText"], 
                          aText = a["InnerText"], 
                          rText = r["InnerText"] 
                      };

我的问题是,有时在“评论”栏中没有匹配的评论,但我仍然希望在我的结果上获得标题和作者。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

您需要左外连接。 http://solidcoding.blogspot.com/2007/12/left-outer-join-in-linq.html

另一个具有多个左外连接的示例:Linq to Sql: Multiple left outer joins

答案 1 :(得分:0)

确定这有效,但不确定为什么:

        var title = dataSet.Tables["title"].AsEnumerable();
        var author = dataSet.Tables["author"].AsEnumerable();
        var review = dataSet.Tables["review"].AsEnumerable();

        var results = from t in title
                      join a in author on t["Url"] equals a["Url"]
                      join r in review on t["Url"] equals r["Url"] into g
                      from r in g.DefaultIfEmpty() 
                      select new { 
                          tText = t["InnerText"], 
                          aText = a["InnerText"], 
                          rText = r != null? r["InnerText"]: ""
                      };