来自不同对象的Sum属性值

时间:2014-11-18 16:02:08

标签: c#

我有以下课程:

public class Data {
  public Decimal DataValueA { get; set; }
  public Decimal DataValueB { get; set; }
  public Decimal DataValueC { get; set; }
  public Decimal DataValueD { get; set; }
} // Data

我有List<Data>。我需要创建一个新的Data对象:

Data total = new Data();

DataValueADataValueAData项中所有List<Data>的总和。

DataValueBDataValueC

相同

我试图用Linq做这个,但现在确定如何。

3 个答案:

答案 0 :(得分:2)

var total = new Data
{
    DataValueA = list.Sum(x => x.DataValueA),
    DataValueB = list.Sum(x => x.DataValueB),
    ...
};

答案 1 :(得分:1)

如果您对该集合的多个枚举都没问题,则可以多次使用list.Sum(item => item.Property)。如果您只浏览一次列表至关重要,例如,因为它是通过延迟执行过滤器生成的,您可以改为使用Aggregate

var totals = list.Aggregate(new Data(), (prev, item) => {
     prev.DataValueA += item.DataValueA;
     prev.DataValueB += item.DataValueB;
     ...
     return prev;
});

答案 2 :(得分:1)

您可以使用Sum,但这将导致列表上的多次迭代:

var total = new Data
{
    DataValueA = list.Sum(x => x.DataValueA),
    DataValueB = list.Sum(x => x.DataValueB),
    DataValueC = list.Sum(x => x.DataValueC),
    DataValueD = list.Sum(x => x.DataValueD),
};

或者您可以Aggregate我们只会迭代列表一次:

var data = new[]{
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
        };

var result = data.Aggregate(new Data(),(a,b) => {
    a.DataValueA += b.DataValueA; 
    a.DataValueB += b.DataValueB;
    a.DataValueC += b.DataValueC;
    a.DataValueD += b.DataValueD;
    return a;
});

实例:http://rextester.com/ODL27846

更多信息:LINQ Aggregate algorithm explained