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.
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.
– M. Victor
@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?
– BrenoSarkis
It didn’t work, I’m not getting the expected amount.
– M. Victor
@user17636 I changed the answer.
– BrenoSarkis
It worked perfectly. Thanks so much for the help, big hug! :)
– M. Victor
@user17636 You are welcome, since it worked, I will change the answer to explain why.
– BrenoSarkis
One more drop of knowledge added to my collection. Thank you!
– M. Victor