Add values present in a List

1

I'll explain what I want to do.
I have this List :

public static List<Cliente> Clientes = new List<Cliente>();

public class Cliente
{
    public string Nome { get; set; }
    public List<ProdutoComprado> Produtos { get; set; }
}

public class ProdutoComprado
{
    public string NomeProduto { get; set; }
    public string ValorProduto { get; set; }
}

As you can see, every customer has their products. What I need is to add the values of the Product Value constant of all products of a given client. I believe that in order to do this I will have to use Sum to add the variables. I was trying something like:

Cliente cliente = Clientes[listaClientes.SelectedIndex];

int total = 0;
foreach (var s in cliente.Produtos)
{
    total = s.ValorProduto.Sum(x => Convert.ToInt32(x));
}

string soma = string.Format("\n\n\nValor total: {0}", total);

This is not working. I am having output as the value 317.

    
asked by anonymous 07.11.2014 / 17:28

1 answer

1

Try changing the code to the following:

Cliente cliente = Clientes[listaClientes.SelectedIndex];

int total = cliente.Produtos.Sum(x => Convert.ToInt32(x.ValorProduto));

string soma = string.Format("\n\n\nValor total: {0}", total);

LINQ Sum acts by traversing and adding list elements, so the external foreach is unnecessary. Another point that is failing in your code is that you are always overwriting the total and not incrementing it (changing the = by + =).

    
07.11.2014 / 17:36