Adding values present in a List

Asked

Viewed 6,384 times

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 constant Valorproduto of all products of a particular customer. I believe that 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 as output the value 317.

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);

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

  • haha' I knew someone would ask this. I particularly like to use string to store values regardless of type. When I need to perform some operation with a certain value, I use the conversion. In this case, I convert the string to int with Convert.Toint32.

  • @user17636 All right with your personal preference, but when you work as a team, I suggest you rethink this. That’s a very unsafe attitude, and I can’t think of a good reason to defend it. Imagine how many conversion problems you might have... languages have multiple types for a reason. But as to the original question, it worked?

  • It didn’t work, I’m not getting the expected amount.

  • @user17636 I changed the answer.

  • It worked perfectly. Thanks so much for the help, big hug! :)

  • @user17636 You are welcome, since it worked, I will change the answer to explain why.

  • One more drop of knowledge added to my collection. Thank you!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.