linq sum group by from a list

-1

Hello I have a list of Articles of the Article class

public class Articulo
{
    public Int32 IdArticulo { get; set; }
    public decimal Cantidad { get; set; }
    public string Estado { get; set; }
}

well, from this list, I need to add the number of items grouped by your article ID, this I want to run in linq.

Any ideas on how to do this? Greetings and thanks

    
asked by Luis Gabriel Fabres 13.10.2017 в 21:14
source

1 answer

3

As soon as I understand you, do you want to add the list based on the id?

public class Articulo
{
    public Int32 IdArticulo { get; set; }
    public decimal Cantidad { get; set; }
    public string Estado { get; set; }
    public int IdGrupo { get; set; }
}
var lstArticulos = ConsultaTodosArticulosDesdeBD();

var LstGrupoSumado = lstArticulos.GroupBy(l => l.IdGrupo)
                          .Select(la => 
                                new { 
                                    IdGrupo = la.Key, 
                                    NoArticulos= la.Count(),
                                    SumaCantidad = la.Sum(s => s.Cantidad), 
                                }).toList();

This is the way to work with lambda expressions.

First they are grouped with GroupBy () , in this case by their Id. After Select () will assign each of its values. If you notice, this GroupBy keeps the data as List being within the Select. And answering your question, the sum is done with the function Sum ()

    
answered by 13.10.2017 / 22:06
source