我是LINQ lambda表达式的新手,我在下面的问题上已经被困了一段时间。 我想执行左外连接并且想要选择左表而不是右表但是当我选择左表时,下面的查询给出了错误
"查询"是一个IQueryable,也是" model2"
var model = query.GroupJoin(model2,
o => o.plu,
m => m.plu,
(o, m) => new
{
SmartCoupon = o,
Product = m.DefaultIfEmpty(),
})
.SelectMany
(
a => a.SmartCoupon
);
下面是使用右表的正确查询,但我需要左表
var model = query.GroupJoin(model2,
o => o.plu,
m => m.plu,
(o, m) => new
{
SmartCoupon = o,
Product = m.DefaultIfEmpty(),
})
.SelectMany
(
a => a.Product
);
答案 0 :(得分:5)
你误解了SelectMany()
。
它用于在此处需要Select()
的另一个列表中展平List:
.Select(a => a.SmartCoupon);
假设您有List<List<string>>`` and you want all string in a
列表, then you need to use
SelectMany()`。
var nameList = new List<List<string>>()
{
new List<string>
{
"Matt","Adam","John","Peter","Owen"
},
new List<string>
{
"Tim","Jim","Andy","Fred","Todd"
}
};
现在使用SelectMany()
获取单个IEnumerable<string>
,如果您使用选择它将返回IEnumerable<IEnumerable<string>>
:
var namesInSingleList = nameList.SelectMany(x => x);
您可以看到difference between Select and SelectMany in this SO post