How to achieve row_number over partition by LINQ

Sudip Bhatt 2,281 Reputation points
2021-02-17T16:14:01.037+00:00

See sample sql

SELECT
*
,Row_Number() OVER (PARTITION BY inst ORDER BY id) AS rn
FROM Beatles

How to write same kind of query by LINQ?

Please suggest.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-02-17T16:51:35.057+00:00

    Try something like this:

    var query =
        Beatles
           .GroupBy( b => b.inst )
           .SelectMany( g => g.OrderBy( b => b.id ).Select( ( b, i ) => new { b.inst, b.id, rn = i + 1 } ) );
    
    var results = query.ToList( );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.