Domanda

How can the following Generic List be summed up by total cost? Meaning is it possible to add both costs below to get a total?

Model:

public class Product
{
      public string Name {get;set;}
      public int Cost  {get;set;}
}

Now I want to use that model in a Generic list like this:

public void GetTotal()
{
     IList<Product> listOfJediProducts = new List<Product>();

     Product newProduct1 = new Product();
     newProduct1.Name = "LightSaber";
     newProduct1.Cost = 1500;
     listOfJediProducts.Add(newProduct1);

     Product newProduct2 = new Product();
     newProduct2.Name = "R2RobotSpec9";
     newProduct2.Cost = 5000;
     listOfJediProducts.Add(newProduct2);
 }

How would I return say a Total for Products in list?

È stato utile?

Soluzione

listOfJediProducts.Sum(p => p.Cost);

This runs the selector lambda expression over each element in the sequence (returning Cost in this case). The Sum function is then run on the "implicitly returned" IEnumerable, which obviously calculates the sum and returns it.

It is worth noting that the above is similar to writing:

listOfJediProducts.Select(p => p.Cost).Sum();

Which may be a little more obvious (if not verbose) in understanding what my first example does.

I say "implicitly returned" because Sum only makes sense on an IEnumerable of numbers, the internal workings are probably doing something closer to this:

int total;
foreach (Product p in listOfJediProducts)
   total += p.Cost;

return total;

Altri suggerimenti

else, using foreach loop

int total_cost = 0;
foreach (Product p in listOfJediProducts)
{
 total_cost+= p.cost;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top