简体   繁体   中英

Sum values on list sorted by Distinct C#

I have a list in C# with this kind of data:

REST CENA 5
REST COMIDAS 3
REST DESAYUNO 4
VIPP CENA 52
VIPP COMIDAS 31
VIPP DESAYUNO 45
REST CENA 2
REST COMIDAS 8
REST DESAYUNO 87
VIPP CENA 12
VIPP COMIDAS 325
VIPP DESAYUNO 21

and I would like to be able to display on an input in HTML the sum of all the data for REST, VIPP, COMIDAS, DESAYUNOS and CENA, like this

 @foreach (var item in Model.Select(l => l.Pdv).Distinct()) <input value="@item"> } @* 

But this only give me the values of REST and VIPP witch is fine but i would like to also sum al values of REST and VIPP like this

REST 109
VIPP 486

and also be able to get

CENA 71
COMIDAS 367
DESAYUNO 293

I know I need 6 separate queries but how can I write those?

You can do that with a GroupBy

foreach(var item in Model.GroupBy(l => l.Pdv)
                         .Select(g => new 
                                      {
                                          Pdv = g.Key, 
                                          Sum = g.Sum(l => l.WhateverYouAreSumming) 
                                       }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM