LINQ中的分组依据和和子句 [英] Group By and Sum clauses in LINQ
问题描述
我编写了一个简单的linq查询,如下所示:
I've written a simple linq query as follows:
var query = from c in context.ViewDeliveryClientActualStatus
join b in context.Booking on c.Booking equals b.Id
join bg in context.BookingGoods on c.Booking equals bg.BookingId
select new { c, b, bg };
我已经用多个前提过滤了先前的查询,然后需要按一组字段分组并获取其中一些字段的总和,如下所示:
I have filtered the previous query with a number of premises and then needed to group by a set of fields and get the sum of some of them, as so:
var rows = from a in query
group a by new {h = a.c.BookingRefex, b = a.c.ClientRefex, c = a.b.PickupCity, d = a.b.PickupPostalCode} into g
select new
{
Booking_refex = g.Key.h,
Client_refex = g.Key.b,
//Local = g.
Sum_Quan = g.Sum(p => p.bg.Quantity),
};
我想从a
中获取一些我未包含在group by子句中的值.我如何获得这些价值?无法通过g
访问它们.
I'd like to get a few values from a
which I haven't included in the group by clause. How can I get those values? They're not accessible through g
.
推荐答案
您的LINQ表达式中的g
是一个IEnumerable
,其中包含具有额外属性Key
的a's
.如果要访问不属于Key
的a
字段,则必须执行某种聚合或选择.如果您知道该组中所有元素的特定字段都相同,则可以从组中的第一个元素中选择该字段的值.在此示例中,我假设c
有一个名为Value
的字段:
The g
in your LINQ expression is an IEnumerable
containing a's
with an extra property Key
. If you want to access fields of a
that are not part of Key
you will have to perform some sort of aggregation or selection. If you know that a particular field is the same for all elements in the group you can pick the value of the field from the first element in the group. In this example I assume that c
has a field named Value
:
var rows = from a in query
group a by new {
h = a.c.BookingRefex,
b = a.c.ClientRefex,
c = a.b.PickupCity,
d = a.b.PickupPostalCode
} into g
select new {
BookingRefex = g.Key.h,
ClientRefex = g.Key.b,
SumQuantity = g.Sum(p => p.bg.Quantity),
Value = g.First().c.Value
};
但是,如果组中的c.Value
相同,则最好将其包含在分组中,并使用g.Key.cValue
进行访问.
However, if c.Value
is the same within a group you might as well include it in the grouping and access it using g.Key.cValue
.
这篇关于LINQ中的分组依据和和子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!