Selecting Consecutive Entries with LINQ to Entities

前端 未结 4 2003
野性不改
野性不改 2021-01-12 20:34

I have a database table with rows that each contain a sequential index. I want to select groups of rows that are consecutive based upon this index column. For example, if I

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 21:06

    So I think I've come up with a pretty good solution modeled after Brian's answer in the topic I linked to.

    var q = from a in query
            from b in query
            where a.Index < b.Index
            && b.Index < a.Index + 3
            group b by new { a.Index }
                into myGroup
                where myGroup.Count() + 1 == 3
                select myGroup.Key.Index;
    

    Change 3 to the number of consecutive rows you want. This gives you the first index of every group of consecutive rows. Applied to the original example I provided, you would get:

    3
    9
    10
    

提交回复
热议问题