Linq Group by Sum Lists Elementwise

时间:2017-09-01 17:15:36

标签: vb.net linq linq-group

所有SC的双打CTable列表大小相同。 我想添加按CTable.Ch分组的SC。结果应该是一个总和列表。是否有操作员/定制?

Public Class SCRow
 Public L As String
 Public Ch As String
 Public SC As List(Of Double)
End Class

Dim CTable AS New List(Of SCRow)

Dim AggrC =
    From C In CTable
    Group C By Key = C.Ch
    Into Group
    Select New With
    {
       .Ch= Key,
       .SumSC = Group.Sum(Function(x)  ???)
    }

Example:

CTable.Add(New SCRow With {.L = "L1", .Ch = "Ch1", .SC = New List(Of Double)(New Double() {1.0, 2.0})})
CTable.Add(New SCRow With {.L = "L1", .Ch = "Ch2", .SC = New List(Of Double)(New Double() {3.0, 4.0})})
CTable.Add(New SCRow With {.L = "L2", .Ch = "Ch1", .SC = New List(Of Double)(New Double() {5.0, 6.0})})


Output:
Ch1 {6=1+5, 8=2+6}
Ch2 {3, 4}

1 个答案:

答案 0 :(得分:1)

可以使用Aggregate扩展方法和Zip方法完成。我用C#编写了代码。请将其翻译为VB.Net。希望它会有所帮助。

聚合:对结果中的每个元素执行指定的操作,同时向前传递结果。

Zip: Zip扩展方法对两个集合起作用。它将两个系列中的每个元素一起处理。

public class SCRow
{
    public string L { get; set; }
    public string CH { get; set; }
    public List<double> SC { get; set; }
}
class Program
{

    static void Main(string[] args)
    {
        var CTable = new List<SCRow>{
            new SCRow { L = "L1",  CH = "Ch1", SC = new List<double> { 1.0, 2.0}},
            new SCRow { L = "L1",  CH = "Ch2", SC = new List<double> { 3.0, 4.0}},
            new SCRow { L = "L2",  CH = "Ch1", SC = new List<double> { 5.0, 6.0}},
        };

        var result = CTable.GroupBy(c => c.CH)
            .Select(x => new
            {
                Value = x.Aggregate((curr, next) => new SCRow
                {
                    CH = x.Key,
                    SC = curr.SC.Zip(next.SC, (n1, n2) => n1 + n2).ToList()
                })
            })
            .Select(y => new {
              CH = y.Value.CH,
              ScSum = y.Value.SC
            }).ToList();

    }
}