C# 使用LINQ而不使用中间步骤的稠密_-RANK()
我让SQL SERVERC# 使用LINQ而不使用中间步骤的稠密_-RANK(),c#,sql-server,entity-framework,linq,linq-to-sql,C#,Sql Server,Entity Framework,Linq,Linq To Sql,我让SQL SERVERRANK()函数通过以下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 =&
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
});
我想如果我不能直接获得densed\u-RANK()
,我可以观察RANK()
的变化,并尝试基于此选择densed\u-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 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();
谢谢我用这种方法实现了它,尽管我不能根据实际的db结果分组,因为它非常慢。我已经把细节写进了答案你不需要一个叫orderby的人来获得排名吗?否则,您只有一个索引号。
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();