如何使用LINQ在List中的类中添加两个字段?

时间:2017-12-07 18:34:00

标签: c# linq linq-to-entities linq-to-objects

我在这里查看了一些答案,但找不到我想要的答案。 所以,我决定发布这些问题:

我有A类的对象,我有一个List<A>

类具有以下定义:

    public decimal Discount { get; set; }
    public decimal Deposit { get; set; }
    public decimal Total { get; set; }

我在列表中有很多这样的课程。

我计算了折扣和存款总额:

var DepositTotal = myList.Sum(x => x.Deposit);
var DiscountTotal = myList.Sum(x => x.Deposit);

现在,我需要计算每个班级的总和(存款,折扣)并将结果分配到Total字段,这样我以后就可以为每个班级获得Total

我该怎么做?

2 个答案:

答案 0 :(得分:2)

你真的不应该尝试修改LINQ查询中的项目,因为你的代码的读者不会期望它发生。

不幸的是,即使使用Select:

,您也可以轻松完成
    list.Select(x => {x.Total = x.Discount + x.Deposit; return x;});

注意:更好的解决方案可能是计算属性Total而不是字段:

 public decimal Total => Discount + Deposit;

答案 1 :(得分:0)

The way you are currently doing it using setters from Discount and Deposit sounds correct but then you should make your setter for Total private too.

You cannot/should not mutate your list's A objects inside a query but you can update the list by overwriting it using the output of your query on the original list. Not clear on your class A's constructors but something like the following:-

myList = myList.Select(a=>new A(Discount =a.Discount, Deposit=a.Deposit, Total=a.Discount+a.Deposit) ).ToList();

Still if Total is solely dependent on values from Discount and Deposit - as the naming appears to indicate, making this entirely internal to your class - encapsulation - is better.