使用Sum进行分组并将值Linq连接到Object

时间:2015-04-16 16:26:45

标签: c# .net linq-to-objects

我有这个借记对象列表

List<Debit> debits = new List<Debit>()
{
  new Debit { Code = "A001", Length = 100, Qte = 3, Position = "MCD" },
  new Debit { Code = "A001", Length = 100, Qte = 2, Position = "MED" },
  new Debit { Code = "A001", Length = 200, Qte = 1, Position = "MCG" },
  new Debit { Code = "A002", Length = 200, Qte = 1, Position = "MCD" },
  new Debit { Code = "A003", Length = 200, Qte = 1, Position = "TBD" }
};

我尝试按代码和长度对借记进行分组,对分组行的Qte属性求和,并在名为{{Debit的新列表中加入由逗号“,”分隔的位置字符串1}}。

sortedDebit

有没有办法使用sortedDebit : Code = "A001", Length = 100, Qte = 5, Position = "MCD, MED" Code = "A001", Length = 200, Qte = 1, Position = "MCG" Code = "A002", Length = 200, Qte = 1, Position = "MCD" Code = "A003", Length = 200, Qte = 1, Position = "TBD" 来做到这一点?

1 个答案:

答案 0 :(得分:4)

当然有。您可以将两个字段的组合分组为一个新的复合键,这是一个简单的匿名对象。这要求构成新组合键的每个字段都可以通过对象引用进行等同,或者因为它具有有效的GetHashCodeEquals实现。

var grouped = debits
    .GroupBy(d => new { Code = d.Code, Length = d.Length })
    .Select(g => new Debit() {
        Code = g.Key.Code,
        Length = g.Key.Length,
        Qte = g.Sum(x => x.Qte),
        Position = string.Join(", ", g.Select(x => x.Position).Distinct())
    });