linq组按SUM列表元素



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}

可以使用聚合扩展方法以及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();
    }
}

相关内容

  • 没有找到相关文章