LinQ groupby乘以列和总和c#

时间:2016-02-12 05:40:44

标签: c# html linq list foreach

我在c#中有一个项目列表,如下所示:

Rid         Pdv     Total  Quantity
DESAYUNOS   VITP    55        1
CENAS       REST    38        2
COMIDAS     VITP    23        3
DESAYUNOS   REST    116       7
CENAS       VITP    112       1
COMIDAS     REST    11        4
DESAYUNOS   VITP    67        9
CENAS       REST    20        2
COMIDAS     VITP    47        5
DESAYUNOS   REST    5         2
CENAS       VITP    10        1

我想得到一个结果,数量乘以Total和所有不同的“Pdv”和“Rid”的所有总数,我使用GroupBy,但它只计算每个不同的总数“Rid “和”Pdv“

@foreach (var item in Model.GroupBy(l => l.Rid)
    .Select(z => new 
                    { 
                        Turno = z.Key, 
                        Total = z.Sum(l => l.Total) 
                    }))
{
   <input value="@item" />
}

如何使“总计”在Sum之前乘以“Quantity”?

2 个答案:

答案 0 :(得分:1)

你应该这样做:

@foreach (var item in Model
                     .Select(x => new //here you count your total
                     { 
                         Rid = x.Rid, 
                         Total = x.Total * x.Quantity
                     })
                     .GroupBy(l => l.Rid) //and then grouping
                     .Select(z => new 
                     { 
                         Turno = z.Key, 
                         Total = z.Sum(l => l.Total) 
                     }))
{
   <input value="@item" />
}

答案 1 :(得分:0)

我想得到一个结果,数量乘以总数和所有不同的所有总数“ Pdv ”和“ Rid

@foreach (var item in Model
                     .Select(m => new { Rid = m.Rid, m.Pdv, Total =m.Total * m.Quantity})
                     .GroupBy(g => new { g.Rid, g.Pdv} )
                     .Select(s => new 
                     { 
                         Rid = s.Key.Rid, 
                         Pdv = s.Key.Pdv, 
                         Total = s.Sum(t => t.Total) 
                     }))
{
   <input value="@item" />
}