我有以下代码片段,其中我尝试使用左连接。 如果没有找到记录,我想将其显示为“无”。
var customers = new Customer[]
{
new Customer{Code = 5, Name = "Sam"},
new Customer{Code = 6, Name = "Dave"},
new Customer{Code = 7, Name = "Julia"},
new Customer{Code = 8, Name = "Sue"}
};
// Example orders.
var orders = new Order[]
{
new Order{KeyCode = 5, Product = "Book"},
new Order{KeyCode = 6, Product = "Game"},
new Order{KeyCode = 7, Product = "Computer"},
new Order{KeyCode = 7, Product = "Mouse"},
new Order{KeyCode = 8, Product = "Shirt"},
new Order{KeyCode = 5, Product = "Underwear"}
};
var source = customers.GroupJoin(
orders,
p => p.Code,
c => c.KeyCode,
(p, g) => g
.Select(c => new { PID = p.Code, CID = c.KeyCode })
.DefaultIfEmpty(new { PID = 0, CID }))//Error 1 The type arguments for method 'System.Linq.Enumerable.DefaultIfEmpty<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
.SelectMany(g => g);
// Enumerate results.
我了解如何应用群组加入。但是如果我想通过修改上一个查询来显示左外连接记录,需要做哪些更改?
有人请帮助我理解这一点。 分配和变量声明如何发生在这里?
编辑:我修改了,因为我找到了另一篇文章,但在行defaultifempty中收到错误。我是否需要修改任何内容才能使其正常工作?
答案 0 :(得分:0)
我不确定你的例子是什么是X,Y但是你所寻求的答案要简单得多。
这将加入您的2个表,并使用func(订单,客户),您可以选择结果中的哪些参数,或选择整个对象:
var query = orders.Join //Join source table
(customers, //Outer table
m => m.KeyCode, //The foreign key from source to outer table
o => o.Code, //The 'primary' key of target table
(order, customer) => //func for parameters
new { order, customer }).GroupBy(m=>m.customer.Code); //Your Result view
//In sql this is something like:
/* SELECT left.Product,
* right.Name
* from Orders as 'left'
* left join customers as 'right' on
* left.KeyCode == right.Code
*/
foreach (var outerItem in query)
{
Debug.WriteLine("{0} bought...", outerItem.FirstOrDefault().customer.Name);
foreach (var item in outerItem)
{
Debug.WriteLine("Product {0}", item.order.Product);
}
}