from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
Run Code Online (Sandbox Code Playgroud)
你如何将上面的内容写成lambda表达式?我被困在了group into
一边.
Jon*_*eet 48
查询连续(select ... into和group ... into,但不是 join ... into)等同于仅拆分查询表达式.所以我想把你的例子想象成:
var tmp = from x in myCollection
group x by x.Id;
var result = from y in tmp
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
Run Code Online (Sandbox Code Playgroud)
将这些更改为点符号:
var tmp = myCollection.GroupBy(x => x.Id);
var result = tmp.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
Run Code Online (Sandbox Code Playgroud)
然后你可以把它们组合起来:
var tmp = myCollection.GroupBy(x => x.Id)
.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
Run Code Online (Sandbox Code Playgroud)
一旦你弄清楚C#编译器对查询表达式的作用,剩下的就相对简单了:)
myCollection.GroupBy(x => x.Id)
.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
Run Code Online (Sandbox Code Playgroud)
myCollection
.GroupBy(x => x.Id)
.Select(x =>
new
{
Id = x.Key,
Quantity = x.Sum(y => x.Quantity
});
Run Code Online (Sandbox Code Playgroud)