DENSE_RANK() 使用 LINQ,无需中间步骤

DENSE_RANK() using LINQ without intermediary steps

我有 SQL SERVER RANK() 函数通过遵循 URL:


下面的答案似乎可以解决问题:

var customersByCountry = db.Customers
    .GroupBy(c => c.CountryID);
    .Select(g => new { CountryID = g.Key, Count = g.Count() });
var ranks = customersByCountry
    .Select(c => new 
        { 
            c.CountryID, 
            c.Count, 
            RANK = customersByCountry.Count(c2 => c2.Count > c.Count) + 1
        });

我想如果我不能直接得到 DENSE_RANK(),我可以观察 RANK() 何时发生变化,并尝试 select 一个 DENSE_RANK() 基于

var denseRankCounter = 0;

Dictionary<int, int> denseRankWithRank = new Dictionary<int, int>();

denseRankWithRank.Add(customersByCountry[0].RANK, ++denseRankCounter);

for (int x = 1; x < customersByCountry.Count; x++)
{
    if (customersByCountry[x] != customersByCountry[x - 1])
    {
        if (!denseRankWithRank.ContainsKey(customersByCountry[x].RANK))
        {
            denseRankWithRank.Add(customersByCountry[x].RANK, ++denseRankCounter);
        }
    }
}

然后将这些结果应用回结果集,

var denseCustomersByCountry = customersByCountry.Select(c => new
                            {
                                DENSE_RANK = denseRankWithRank[c.RANK],
                                CountryID = c.CountryID
                                // ...  ,any other required 
                            }).ToList();

虽然这有点管用,但似乎超级麻烦。
我想知道是否有没有字典或任何中间步骤的更简单的方法。

尝试以下操作:

            var customersByCountry = db.Customers
                .GroupBy(c => c.CountryID)
                .OrderByDescending(x => x.Count())
                .Select((g,rank) => new { CountryID = g.Key, Count = g.Count(), Rank = rank });

这并不难。
我使用上面 jdweng 的方法让它工作,所以我将其标记为答案。
在我的实际数据库结果中,groupBy 真的很慢,所以我创建了字段的子集,然后进行了实际分组。

var customers = db.Customers.OrderBy(c=>c.CountryID);

    var ranks = customers.Select(c => new 
                                  { 
                                        c.CountryID, 
                                        c.Count, 
                                        RANK = customers.Count(c2 => c2.Count > c.Count) + 1
                                    });


    var denseCustomersByCountry = ranks.GroupBy(r => r.RANK)
                                            .Select((r, idx) => new
                                            {
                                                RANK = r.Key,
                                                COUNT = r.Count(),
                                                DENSE_RANK = idx + 1,
                                                CountryID = r.FirstOrDefault().CountryID
                                            })
                                            .ToList();