如何对通用列表中的项目进行求和<t> </t>

时间:2014-04-29 19:37:29

标签: c# generics

如何通过总费用总结以下通用列表?意思是可以在下面添加两个成本来获得总数吗?

型号:

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

现在我想在这样的Generic列表中使用该模型:

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

我如何回复说出列表中的产品总数?

2 个答案:

答案 0 :(得分:13)

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

这会在序列中的每个元素上运行选择器lambda表达式(在这种情况下返回Cost)。然后在&#34;上隐式返回&#34;运行Sum函数。 IEnumerable,显然计算总和并返回它。

值得注意的是,上述内容类似于写作:

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

在理解我的第一个例子时,可能会更明显(如果不是冗长的话)。

我说&#34;隐含地返回&#34;因为Sum只对IEnumerable数字有意义,所以内部工作可能更接近于此:

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

return total;

答案 1 :(得分:1)

否则,使用foreach循环

int total_cost = 0;
foreach (Product p in listOfJediProducts)
{
 total_cost+= p.cost;
}
相关问题