C# 组联接-左外部联接-无法从用法推断方法“System.Linq.Enumerable.DefaultIfEmpty”的类型参数。错误
我在下面的代码片段中尝试使用左连接。 如果未找到任何记录,我希望将其显示为无C# 组联接-左外部联接-无法从用法推断方法“System.Linq.Enumerable.DefaultIfEmpty”的类型参数。错误,c#,linq,C#,Linq,我在下面的代码片段中尝试使用左连接。 如果未找到任何记录,我希望将其显示为无 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,
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行中出现错误。我需要修改任何东西才能使其正常工作吗
在你的例子中,我不确定什么是X,Y,但你所寻求的答案要简单得多 这将连接两个表,使用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);
}
}
它看起来很复杂,因为您考虑的是演示文稿,而不是预期的对象模型。首先关注后者,前者很容易跟进。用什么逻辑方法来表示内存中丢失的记录?然后集中精力让您的查询返回它。一旦你有了工作,集中精力让你丢失的记录显示为无。不幸的是,你在这个问题上漏掉了太多相关的细节,我看不出有什么办法能给出一个更具体的答案。@hvd。我编辑了我的帖子。我想知道selectmany语法在这里是如何工作的?映射是在什么基础上完成的?好的,通过你的编辑,我看到你还没有完全理解一些基本原理,主要是lambda表达式。我可以推荐你找一个关于这些的好教程,然后在这里重新讨论你的问题吗?它们不是一个很难理解的概念,但在一开始的时候,你可能很难理解,我得到的印象是,在理解了lambda表达式之后,你的问题中还有更多需要回答的问题,最好与解释C语言的特性分开。