0

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

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的总和。所以这将是预期的结果:AmountName

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

我该如何存档?

4

3 回答 3

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

于 2012-08-19T14:11:33.897 回答
1
 var lst = list.GroupBy(g = > g.Name).Select(t = > new
 ClassName()
 {
     Amount = t.Sum(s=>s.Amount), Name = t.Key
 }).ToList();
于 2012-08-19T14:06:45.787 回答
1
var result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount));

或者

List<MyClass> result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount)).ToList();
于 2012-08-19T14:08:56.927 回答