问题描述
关于 Linq 中的左连接已经有很多关于 SO 的问题,我看过的问题都使用 join 关键字来实现所需的结果.
There are a lot of questions on SO already about Left joins in Linq, and the ones I've looked at all use the join keyword to achieve the desired end.
这对我来说没有意义.假设我有 Customer 和 Invoice 表,它们由 Invoice 上的外键 CustomerID 链接.现在我想运行一个包含客户信息以及任何发票的报告.SQL 将是:
This does not make sense to me. Let's say I have the tables Customer and Invoice, linked by a foreign key CustomerID on Invoice. Now I want to run a report containing customer info, plus any invoices. SQL would be:
select c.*, i.* from Customer c left join Invoice i on c.ID = i.CustomerID
从我所看到的关于 SO 的答案来看,人们大多是在建议:
From what I've seen of the answers on SO, people are mostly suggesting:
var q = from c in Customers join i in Invoices.DefaultIfEmpty() on c.ID equals i.CustomerID select new { c, i };
我真的不明白这怎么可能是唯一的方法.Customer 和 Invoice 之间的关系已经由 LinqToSQL 类定义;为什么我必须为 join 子句重复它?如果我想要一个内部连接,那就是:
I really don't understand how this can be the only way. The relationship between Customer and Invoice is already defined by the LinqToSQL classes; why should I have to repeat it for the join clause? If I wanted an inner join it would simply have been:
var q = from c in Customers from i in c.Invoices select new { c, i };
没有指定连接的字段!
我试过了:
var q = from c in Customers from i in c.Invoices.DefaultIfEmpty() select new { c, i };
但这只是给了我与内部连接相同的结果.
but that just gave me the same result as if it were an inner join.
没有更好的方法吗?
推荐答案
你在说什么?那个 from i in c.Invoice.DefaultIfEmpty() 正是一个左连接.
What are you talking about? That from i in c.Invoice.DefaultIfEmpty() is exactly a left join.
List<string> strings = new List<string>() { "Foo", "" }; var q = from s in strings from c in s.DefaultIfEmpty() select new { s, c }; foreach (var x in q) { Console.WriteLine("ValueOfStringIs|{0}| ValueOfCharIs|{1}|", x.s, (int)x.c); }
这个测试产生:
ValueOfStringIs|Foo| ValueOfCharIs|70| ValueOfStringIs|Foo| ValueOfCharIs|111| ValueOfStringIs|Foo| ValueOfCharIs|111| ValueOfStringIs|| ValueOfCharIs|0|