title: How to Add Rownum to GroupBy Linq
body: <p>I have a complex LINQ Query to extract Top students in my university. Here is the query :</p>
  <pre><code>            var query = Db.Students.AsNoTracking().Where(...).AsQueryable();
              var resultgroup = query.GroupBy(st =&gt; new
                  {
                      st.Student.CourseStudyId,
                      st.Student.EntranceTermId,
                      st.Student.StudyingModeId,
                      st.Student.StudyLevelId
                  }, (key, g) =&gt; new
                  {
                      CourseStudyId = key.CourseStudyId,
                      EntranceTermId = key.EntranceTermId,
                      StudyingModeId = key.StudyingModeId,
                      StudyLevelId = key.StudyLevelId,
                      list = g.OrderByDescending(x =&gt; 
                      x.StudentTermSummary.TotalAverageTillTerm).Take(topStudentNumber)
                  }).SelectMany(q =&gt; q.list).AsQueryable();
  </code></pre>
  <p>This Query give me top n students based on 4 parameters and on their TotalAverageTillTerm.</p>
  <p>Now I want to add rownum for each group to simulate Total rank, for example Output is :</p>
  <p><a href="https://i.stack.imgur.com/DzNA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DzNA0.png" alt="enter image description here" /></a></p>
  <p>Now I want to Add TotalRank as rownumber like Sql. In the picture X1=1,X2=2,X3=3 and Y1=1,Y2=2,Y3=3</p>
  <p>If I want to reduce problem. I only work on one group. Code Like this :</p>
  <pre><code>                resultgroup = query.GroupBy(st =&gt; new
                  {
                      st.Student.StudyLevelId
                  }, st =&gt; st, (key, g) =&gt; new
                  {
                      StudyLevelId = key.StudyLevelId,
                      list = g.OrderByDescending(x =&gt; 
                      x.StudentTermSummary.TotalAverageTillTerm)
                       .Take(topStudentNumber)
                  }).SelectMany(q =&gt; q.list).AsQueryable();
  </code></pre>