我正在尝试将我的查询语法翻译成Lambda,我在这里看了几个线程,其中一些:
C# Linq Lambda Left Outer Join
How do you perform a left outer join using linq extension methods
我仍然不明白如何实现我想要的东西。
var suppliersAndBuyers = from s in suppliers
orderby s.District
join b in buyers on s.District equals b.District into buyersGroup
select new
{
SupplierName = s.Name,
s.District,
Buyers = buyersGroup.DefaultIfEmpty(
new Buyer()
{
Name = "No one here",
District = "I dont exist",
})
};
这是我的linq查询,它完美运行,每个供应商都有自己的买家组,而那些没有买家的供应商,只需获取我在DefaultIfEmpty方法中创建的默认买方对象。
我尝试使用方法语法执行以下操作:
var leftOuterJoinBuyer = suppliers.GroupJoin(
buyers,
s => s.District,
b => b.District,
(s, buyersGroup) => new
{
s.Name,
s.District,
Buyers = buyersGroup
})
.SelectMany(s => s.Buyers.DefaultIfEmpty(new Buyer() { Name = "No name", District = "No place", }),
(s, b) => new
{
SupplierName = s.Name,
Buyers = s.Buyers,
s.District
}
);
两种方法都返回完全相同的类型,但我没有得到我的无匹配供应商的默认对象,并且那些有匹配的方法会多次添加到最终结果。
例如,Harrison在最终集合中添加了3次与完全相同的买家集合,基本上3个相同的结果是不需要的,并且不会在我的查询语法中生成。截图 - > https://prntsc/iocsby
重写此查询的正确方法是什么?
答案 0 :(得分:1)
这是lambda版本:
var lambdaQuery = suppliers.GroupJoin(buyers, s => s.District, b => b.District,
(s, buyersGroup) => new {
SupplierName = s.Name,
s.District,
Buyers = buyersGroup.DefaultIfEmpty(new Buyer() { Name = "No one here", District = "I don't exist" })
});