我正在做一些C#编码,我有多个相同类型的对象。例如:
public class Expense
{
public decimal Food{ get; set; }
public decimal Clothing{ get; set; }
public decimal Medical{ get; set; }
}
现在我们有3个人X,Y和Z Expense
。我想创建一个对象" Total"相同类型(Expense
),将所有这些加在一起。
是否有快捷方式来执行此操作而不是单独添加所有这些?
答案 0 :(得分:2)
如果您拥有List<>
(或其他IEnumerable
)中的所有对象,则可以使用Linq。例如,如果您的列表是这样的:
var X = new Expense { Food = 1, Clothing = 2, Medical = 3 };
var Y = new Expense { Food = 1, Clothing = 2, Medical = 3 };
var Z = new Expense { Food = 1, Clothing = 2, Medical = 3 };
var expenses = new List<Expense> { X, Y, Z };
您可以创建一个&#39;总计&#39;使用IEnumerable.Sum()
方法对象开销,如下所示:
var totalExpenses = new Expense
{
Food = expenses.Sum(e => e.Food),
Clothing = expenses.Sum(e => e.Clothing),
Medical = expenses.Sum(e => e.Medical)
};
答案 1 :(得分:0)
您需要的是派生属性
public class Expense
{
public decimal Food{ get; set; }
public decimal Clothing{ get; set; }
public decimal Medical{ get; set; }
public decimal TotalExpense { get { return Food+Clothing+Medical; } }
}
然后将所有费用加起来
List<Expense> expenses = ...
decimal total = expenses.Sum((x)=>x.TotalExpense);