使用 Sum 分组并加入值 Linq to Object
Group by with Sum and joined values Linq to Object
我有这个借方对象列表
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
属性 求和,并在 [= 的新列表中加入由逗号“,”分隔的 Position 字符串13=] 命名为 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"
有没有办法使用 linq
来做到这一点?
当然有。您可以将两个字段组合成一个新的组合键,这是一个简单的匿名对象。这要求构成新组合键的每个字段都可以通过对象引用或因为它具有有效的 GetHashCode
和 Equals
实现而相等。
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())
});
我有这个借方对象列表
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
属性 求和,并在 [= 的新列表中加入由逗号“,”分隔的 Position 字符串13=] 命名为 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"
有没有办法使用 linq
来做到这一点?
当然有。您可以将两个字段组合成一个新的组合键,这是一个简单的匿名对象。这要求构成新组合键的每个字段都可以通过对象引用或因为它具有有效的 GetHashCode
和 Equals
实现而相等。
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())
});