按项目列出c#,并将其他项目相加

时间:2013-11-04 16:58:47

标签: c# linq list

想象一下对象列表:

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};

提前致谢!

5 个答案:

答案 0 :(得分:5)

你可以这样做:

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

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

答案 1 :(得分:3)

您应该可以使用分组。

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();

答案 2 :(得分: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) })

答案 3 :(得分: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现在是:

enter image description here

答案 4 :(得分:0)

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

var groupdObject =list
    .GroupBy(o =>o.Name)
    .Select(g => 
       new 
       {
         Name = g.Key, 
         Total = g.Sum(o=>o.Total)
       });