计算列表中属性的总和 [英] Calculate SUM of a property in list
本文介绍了计算列表中属性的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
public class Summary
{
public string Name { get; set; }
public string Marks { get; set; }
}
带有示例数据
SummaryList.Add(new ActivitySummary() { Name = "ATT", Marks = "200"});
SummaryList.Add(new ActivitySummary() { Name = "CHARTER", Marks ="600"});
我想将另一个列表项添加到包含总计标记"属性的列表中.
I want to add another List item to the list that would contain Total of Marks property.
SummaryList.Add(new ActivitySummary() { Name = "TOTAL", Marks ="800"});
如何使用LINQ计算标记的总和?
How can I calculate the SUM of Marks property using LINQ?
推荐答案
要计算总和,请使用Sum
:
SummaryList.Add(new ActivitySummary() {
Name = "TOTAL",
Marks = SummaryList.Sum(item => Convert.ToInt32(item.Marks)).ToString()
});
如果您的Marks
属性仅包含整数,则将其设置为string
类型是没有意义的.如果查询的类型为int
:
If your Marks
property only contains integer numbers, making it of type string
makes no sense. You can simplify the query if it is of type int
:
public class Summary
{
public string Name { get; set; }
public int Marks { get; set; }
}
SummaryList.Add(new ActivitySummary() {
Name = "TOTAL",
Marks = SummaryList.Sum(item => item.Marks)
});
如果您的Marks
属性不是整数,请使用decimal
,float
或double
代替int
(分别是Convert.ToDecimal
,Convert.ToSingle
和Convert.ToDouble
).
If your Marks
property is not an integer number, use decimal
, float
or double
instead of int
(and Convert.ToDecimal
, Convert.ToSingle
and Convert.ToDouble
respectively).
这篇关于计算列表中属性的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文