Linq c#group / sum很多专栏

时间:2015-12-16 10:34:36

标签: c# linq sum

我有一个List对象(属性超过250的对象),我想通过两列(字符串)进行分组,然后对所有其余的(双)进行求和, 是否有任何解决方案可以避免一个接一个地进行求和,并为所有双重属性执行此操作,

此列表我是从XML文件而不是从数据库查询中获取的

var xx = Data.MyList.GroupBy(grp => new MyObject()
            {
                Name = grp.Name,
                Date = grp.Date,

            }).Select(slt => new MyObject()
            {
                Name = slt.Key.Name,
                Date = slt.Key.Date,

                eq = slt.Sum(x=>x.eq),
                eq1 = slt.Sum(x=>x.eq1),
                eq2 = slt.Sum(x=>x.eq2),
                eq3 = slt.Sum(x=>x.eq3),
                .
                .
                .
                eq250 = slt.Sum(x=>x.eq2505),
                }).ToList();

感谢HimBromBeere,这是解决方案

 var grpBySub = Data.MyList.GroupBy(grp => new
        {
             grp.Name,
             grp.Date,
        }).Select(slt => new 
        {
            slt.Key.Name,
            slt.Key.Date,
            Sums = typeof(MyObject).GetProperties().Where(y =>
                y.Name != "Name" &&
                y.Name != "Date" &&

                ).Select(p => new
            {
                p.Name,
                Sum = slt.Sum(entity => ((double?)p.GetValue(entity, null))) 

            }).ToList()

        }).ToList();

2 个答案:

答案 0 :(得分:1)

嗯,虽然对于一个实体来说可能设计了这么多属性的设计很糟糕,但你可以使用反射来获取属性值并将它们相加:

var properties = typeof(MyEntity).GetProperties().ToList();
myEntities.GroupBy(x => x.numerator)
        .Select(x => new
        {
            Key = g.Key,
            Sums = properties.Select(p => new 
            { 
                Name = p.Name, 
                Sum = g.Sum(entity => (int)p.GetValue(entity, null)) 
            }).ToList()
        }).ToList();

答案 1 :(得分:0)

由于您是在XML文档上进行的,因此不一定需要求助于反射。一个非常粗略和未完成的例子:

var xml = @"<root>
               <element groupAttr1=""1"" groupAttr2=""2"" someAttr1=""1"" someAttr2=""2"" />
               <element groupAttr1=""1"" groupAttr2=""2"" someAttr1=""3"" someAttr2=""4"" />
            </root>";

var xDoc = XDocument.Parse(xml);

var groupped = xDoc.Root
                   .Elements("element")
                   .GroupBy(el => new
                                  {
                                     GroupAttr1 = el.Attribute("groupAttr1")?.Value,
                                     GroupAttr2 = el.Attribute("groupAttr2")?.Value
                                  })
                   .Select(x => new
                                {
                                   Key = x.Key,
                                   Sums = x.Select(
                                      el => el.Attributes()
                                              .Where(a => a.Name != "groupAttr1"
                                                       && a.Name != "groupAttr2")
                                              .Sum(a => double.Parse(a.Value)))
                                });