按属性汇总列表

时间:2012-08-19 14:01:22

标签: c# list

我有一个像这样的对象列表:

List<ClassName> list = new List<ClassName>();
list.Add(new ClassName()
{
    Name = 1,
    Amount = 5
});
list.Add(new ClassName()
{
    Name = 2,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 1,
    Amount = 20
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 15
});

现在我想通过属性Name来总结这个列表。结果应包含每个Name的一个条目以及具有相同Amount的条目的Name的总和。 所以这将是预期的结果:

List<ClassName> list = new List<ClassName>();
list.Add(new ClassName()
{
    Name = 1,
    Amount = 25
});
list.Add(new ClassName()
{
    Name = 2,
    Amount = 10
});
list.Add(new ClassName()
{
    Name = 3,
    Amount = 25
});

我如何存档?

3 个答案:

答案 0 :(得分:2)

通过LINQ做到:

var result = list.GroupBy(x => x.Name)
    .Select(x => new ClassName { Name = x.Key, Amount = x.Sum(i => i.Amount) })
    .ToList();

在此处阅读有关LINQ的更多信息:http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

答案 1 :(得分:1)

 var lst = list.GroupBy(g = > g.Name).Select(t = > new
 ClassName()
 {
     Amount = t.Sum(s=>s.Amount), Name = t.Key
 }).ToList();

答案 2 :(得分:1)

var result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount));

OR

List<MyClass> result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount)).ToList();