I have a List
...
MyObject has a propert called LineId (integer)...
So, I need separate all consecutive LineId in List
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.