A
The method GroupBy returns a grouping structure.This structure contains all the data of the grouping concerned and also the key (Key) of it — is key is responsible for the grouping. For example, in your case, you want to group the items by the property NumeroCarroId and therefore it is this property that you pass as parameter to the method GroupBy and, consequently, it turns the key (property Key) of this grouping structure which is returned.Then you can work on top of this structure and use the method Count() to return the amount of elements of each grouping, or Sum() to sum the values of some property and so on.Let's go to an illustrated example, imagine you have the following structure in your tableNumberCaroId | Litro | TotalGasto
1 | 10 | 50
1 | 15 | 75
2 | 10 | 50
2 | 30 | 150
2 | 05 | 25
By doing thistabela.GroupBy(x => x.NumeroCarroId)
The result will be a structure like this[sighs]
{
Key: 1,
_Items: [
{ NumberCaroId: 1, Liter: 10, TotalGasto: 50 },
{ NumberCaroId: 1, Liter: 15, TotalGasto: 75 }
]
)
{
Key: 2,
_Items: [
{ NumberCaroId: 2, Liter: 10, TotalGasto: 50 },
{ NumberCaroId: 2, Liter: 30, TotalGasto: 150 },
{ NumberCaroId: 2, Liter: 05, TotalGasto: 25 },
]
)
)
Note that this is a mere simplified illustration to simulate the structure returned by the method GroupBy.Each item of this structure is the gp No Select belowtabela.GroupBy(x => x.NumeroCarroId)
.Select(gp => new
{
NumeroCarroId = gp.Key,
LitroTotal = gp.Sum(c => c.Litro),
TotalConsumido = gp.Sum(c => c.TotalGasto)
});
From it, you can use the method ToList to get all of her items, the method Sum to add a certain property, the method Count to count the items of each grouping and some other things.The code, using the method syntax (what you are calling lambda) would look like this:var resultado = consulta.GroupBy(c => c.NumCarroId)
.Select(gp => new
{
NumeroCarroId = gp.Key,
LitroTotal = gp.Sum(c => c.Litro),
TotalConsumido = gp.Sum(c => c.TotalGasto)
});