Implementing RANK OVER SQL Clause in C# LINQ

c#, linq, linq-to-objects, sql, t-sql

Solution

If you don't need the exact Rank semantics (i.e. tied ranks). You can use the index available with select projections

var rank = data.GroupBy(d => d.CategoryKey)
               .SelectMany(g => g.OrderByDescending(y => y.Rate * @BAES_RATE)              
                                 .Select((x,i) => new{g.Key, Item=x, Rank=i+1}))

Otherwise you can look at this answer

Problem

I need to implement the following T-SQL clause .... ``` RANK() OVER (PARTITION BY a.CategoryKey ORDER BY (x.Rate * @BASE_RATE ) DESC )as Rank ``` ...in C# LINQ. So far what I've come up with is something like .... ``` var rank = data.GroupBy(d => d.CategoryKey) .Select(group => group.OrderByDescending(g => g.Rate * @BAES_RATE) ``` I think this would give me each rank partition ordered by rate * BASE_RATE. But what I actually need is the individual rank of a single row, with this being a subquery within a larger result. So really the full SQL query I'm working from is something like .... ``` SELECT a.Rate, a.CategoryKey, a.ID, . . . RANK() OVER (PARTITION BY a.CategoryKey ORDER BY (x.Rate * @BASE_RATE ) DESC )as Rank FROM data ```

Original source

Related problems