0

想象一个对象列表:

public class Foo
{
    public string Name {get; set;}
    public int Total {get; set;}
}

现在,我的列表包含 3 个对象:

new Foo {Name="object", Total=3};
new Foo {Name="object", Total=7};
new Foo {Name="object", Total=5};

如何按名称区分并汇总总数?即列表将只有一个对象:

new Foo {Name="object", Total=15};

提前致谢!

4

5 回答 5

5

你可以这样做:

var newTotalList = yourList.GroupBy(x => x.Name)
    .Select(x => new
        {
            Name = x.Key,
            Total = x.Sum(y => y.Total)
        })
    .ToList();

这段代码的作用很简单,首先按名称对元素进行分组,然后对组内所有元素的 Total 字段求和。

于 2013-11-04T17:02:05.010 回答
4

您应该能够使用分组。

var groupedList = (from ol in objectList

                    group ol by ol.Name
                        into grp
                        select new foo
                        {
                            Name = grp.Key,
                            Total= grp.Sum(ex => ex.Total),
                            City = grp.Select(ex => ex.City).FirstOrDefault(),
                            Country = grp.Select(ex => ex.Country ).FirstOrDefault(),
                            Phone = grp.Select(ex => ex.Phone).FirstOrDefault()
                        }
    ).ToList();
于 2013-11-04T17:02:04.643 回答
0

试试这个:

List<Object> list = ... // make a list somehow
var totalsPerName = list
    .GroupBy(o => o.Name)
    .Select(group => new Object { Name = group.Key, Total = group.Sum(o => o.Total) })
于 2013-11-04T17:02:12.690 回答
0

您可以按以下方式分组Name ,然后按以下方式汇总Total

var l = new List<Object>
{
    new Object {Name="object", Total=3},
    new Object {Name="object", Total=7},
    new Object {Name="object", Total=5}
};

var result = l.GroupBy(o => o.Name)
              .Select (grp => new Object 
                            { 
                                Name = grp.Key, 
                                Total = grp.Sum(o => o.Total)
                            });

result就是现在:

在此处输入图像描述

于 2013-11-04T17:02:25.997 回答
0

按名称对元素进行分组,然后为每个组选择一个名称为该组的名称值分组依据的新对象,总计是该组中所有总计的总和:

var groupdObject =list
    .GroupBy(o =>o.Name)
    .Select(g => 
       new 
       {
         Name = g.Key, 
         Total = g.Sum(o=>o.Total)
       });
于 2013-11-04T17:04:41.460 回答