C# 如何在LINQtoSQL中使用orderby和partition by获取最顶层行
我想返回2条得分最高的记录。王牌2分,吉姆3分。 我在sql中这样做了,但我似乎无法在linq中正确地转换它。 SQl查询:C# 如何在LINQtoSQL中使用orderby和partition by获取最顶层行,c#,sql,linq-to-sql,entity-framework-core,C#,Sql,Linq To Sql,Entity Framework Core,我想返回2条得分最高的记录。王牌2分,吉姆3分。 我在sql中这样做了,但我似乎无法在linq中正确地转换它。 SQl查询: Table id | name | score ----------------- 3 | jim | 2 4 | jim | 1 5 | jim | 3 6 | Ace | 2 7 | Ace | 1 以下是我在linq开始的工作: SELECT * FROM (SELECT Row_number()
Table
id | name | score
-----------------
3 | jim | 2
4 | jim | 1
5 | jim | 3
6 | Ace | 2
7 | Ace | 1
以下是我在linq开始的工作:
SELECT *
FROM (SELECT Row_number()
OVER(
partition BY name
ORDER BY score DESC) AS rn,
score,
id,
name,
FROM table ) AS a
WHERE rn = 1
谢谢您的帮助。您可以尝试这种方式,现场演示
ctx.records.orderbydowningr=>r.score.GroupByr=>r.name.Selectg=>g.FirstOrDefault.ToList@是他干的。非常感谢。
ctx.records.GroupBy(r => r.name).Select(g => g.OrderByDescending(i => i.score)).ToList();
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var records = new []
{
new Record { id = 3, name = "jim", score = 2 },
new Record { id = 4, name = "jim", score = 1 },
new Record { id = 5, name = "jim", score = 3 },
new Record { id = 6, name = "Ace", score = 2 },
new Record { id = 7, name = "jim", score = 1 }
};
var result = records.GroupBy(p => p.name)
.Select(g => new { Name = g.Key, Score = g.Max(p => p.score) })
.ToList();
foreach(var item in result)
Console.WriteLine("Name: " + item.Name + " Score: " + item.Score);
}
public class Record
{
public int id {get; set;}
public string name {get; set;}
public int score {get; set;}
}
}