【发布时间】:2020-06-21 13:10:27
【问题描述】:
我的 SQL SERVER RANK() 函数通过以下 URL 工作:
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();
虽然这有点工作,但它似乎超级麻烦。
我想知道是否有没有字典或任何中间步骤的更简单的方法。
【问题讨论】:
标签: c# sql-server entity-framework linq linq-to-sql