How to separate all consecutive Objects using Linq (C#)

后端 未结 6 629
长发绾君心
长发绾君心 2021-01-14 10:37

I have a List ... MyObject has a propert called LineId (integer)...

So, I need separate all consecutive LineId in List

6条回答
  •  终归单人心
    2021-01-14 11:17

    This looks ugly but the idea is clear and I think it works:

    var agg = list.Aggregate(
        new List>(),
        (groupedLines, line) => {
            if (!groupedLines.Any()) {
                groupedLines.Add(new List() { line });
            }
            else {
                List last = groupedLines.Last();
                if (last.First().LineId == line.LineId) {
                    last.Add(line);
                }
                else {
                    List newGroup = new List();
                    newGroup.Add(line);
                    groupedLines.Add(newGroup);
                }
            }
            return groupedLines;
        }
    );
    

    Here I am assuming that you have:

    class Line { public int LineId { get; set; } }
    

    and

    List list = new List() {
        new Line { LineId = 1 },
        new Line { LineId = 1 },
        new Line { LineId = 1 },
        new Line { LineId = 2 },
        new Line { LineId = 1 },
        new Line { LineId = 2 }
    };
    

    Now if I execute

    foreach(var lineGroup in agg) {
        Console.WriteLine(
            "Found {0} consecutive lines with LineId = {1}",
            lineGroup.Count,
            lineGroup.First().LineId
        );
        foreach(var line in lineGroup) {
            Console.WriteLine("LineId = {0}", line.LineId);
        }
    }
    

    I see:

    Found 3 consecutive lines with LineId = 1
    LineId = 1
    LineId = 1
    LineId = 1
    Found 1 consecutive lines with LineId = 2
    LineId = 2
    Found 1 consecutive lines with LineId = 1
    LineId = 1
    Found 1 consecutive lines with LineId = 2
    LineId = 2
    

    printed on the console.

提交回复
热议问题