I have a List
...
MyObject has a propert called LineId (integer)...
So, I need separate all consecutive LineId in List
A slightly smaller solution, but probably (read: definitely) less clear:
var lst = new [] {
new { LineID = 1 },
new { LineID = 1 },
new { LineID = 1 },
new { LineID = 2 },
new { LineID = 1 },
new { LineID = 2 },
};
var q = lst
.Select((x,i) => new {Item = x, Index = i})
.GroupBy(x => x.Item)
.SelectMany(x => x.Select((y,i) => new { Item = y.Item, Index = y.Index, Sort = i - y.Index }))
.OrderBy(x => x.Index)
.GroupBy(x => x.Sort)
.Select(x => x.Select(y => y.Item));
Returns an IEnumerable
:
1,1,1
2
1
2
Note, if you don't care about order, you can remove the 'OrderBy' line and the 'Index = y.Index' property in the anonymous object and it will return:
1,1,1
1
2
2