无需中间步骤即可使用LINQ进行DENSE_RANK()

时间:2020-03-09 15:46:47

标签: c# sql-server entity-framework linq linq-to-sql

通过遵循以下网址,我可以使用SQL SERVER RANK()函数:

https://stackoverflow.com/questions/27469838/is-there-a-function-in-entity-framework-that-translates-to-the-rank-function-i?noredirect=1&lq=1

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

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()何时发生变化,并尝试根据此选择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();

尽管这种方法有些奏效,但似乎非常麻烦。
我想知道是否有没有字典或任何中间步骤的简便方法。

2 个答案:

答案 0 :(得分:1)

尝试以下操作:

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

答案 1 :(得分:0)

这太难了。
我可以使用上面的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();
相关问题