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

后端 未结 6 623
长发绾君心
长发绾君心 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:29

    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
    

提交回复
热议问题