LINQ query — Data aggregation (Group Adjacent)

前端 未结 7 1990
失恋的感觉
失恋的感觉 2020-12-03 03:09

Let\'s take a class called Cls:

public class Cls
{
    public int SequenceNumber { get; set; }
    public int Value { get; set; }
}
相关标签:
7条回答
  • 2020-12-03 04:12

    Here is an implementation without any helper methods:

    var grp = 0;
    var results =
    from i
    in
    input.Zip(
        input.Skip(1).Concat(new [] {input.Last ()}),
        (n1, n2) => Tuple.Create(
            n1, (n2.Value == n1.Value) ? grp : grp++
        )
    )
    group i by i.Item2 into gp
    select new {SequenceNumFrom = gp.Min(x => x.Item1.SequenceNumber),SequenceNumTo = gp.Max(x => x.Item1.SequenceNumber), Value = gp.Min(x => x.Item1.Value)};
    

    The idea is:

    • Keep track of your own grouping indicator, grp.
    • Join each item of the collection to the next item in the collection (via Skip(1) and Zip).
    • If the Values match, they are in the same group; otherwise, increment grp to signal the start of the next group.
    0 讨论(0)
提交回复
热议问题