如何使用 LINQ 获取列中具有最大值的所有唯一记录

huangapple go评论60阅读模式
英文:

How to get all unique records with the maximum value in column using LINQ

问题

给定这些数据,如何获取所有具有最高尝试次数的独特学生姓名?
我尝试获取以下结果:

    学习者      | 评估Id     | 尝试次数 
    ------------------------------------
    Parker    |     1       |    3    
    Stark       |     1       |    1    
    Rogers      |     1       |    2    

我该如何在LINQ中用单个查询来实现这个目标?

    from la in _context.LearnerAssessments
    where la.AssessmentId == assessmentId
      && learnerIds.Contains(la.LearnerId)
      && la.Attempt == {最高尝试次数}
英文:
Learner     | AssesmentId | Attempt 
------------------------------------
Parker      |     1       |    1    
Parker      |     1       |    2    
Stark       |     1       |    1    
Rogers      |     1       |    1    
Rogers      |     1       |    2    
Parker      |     1       |    3    

Given this data, how do I get all the unique Student name with the highest Attempt?
I'm attempting to get this result:

Learner     | AssesmentId | Attempt 
------------------------------------
Parker      |     1       |    3    
Stark       |     1       |    1    
Rogers      |     1       |    2    

How can I do this in a single query in LINQ?

from la in _context.LearnerAssessments
where la.AssessmentId == assessmentId
  && learnerIds.Contains(la.LearnerId)
  && la.Attempt == {highest attempt}

答案1

得分: 2

以下是您要翻译的代码部分:

var data = from list in _context.LearnerAssessments
           group list by new
    {
        list.Learner,
        list.AssesmentId
    }
    into g
    select new
    {
        g.Key.Learner,
        g.Key.AssesmentId,
        Max= g.Max(x=>x.Attempt)
    };

或者使用 Fluent API:

var data = _context.LearnerAssessments.GroupBy(l => new { l.Learner, l.AssesmentId }, (keys, item) => new
{
    Key = keys,
    MaxAttemp = item.Max(x => x.Attempt)
}).Select(x => new LearnerAssessment
{
    Learner = x.Key.Learner,
    Attempt = x.MaxAttemp,
    AssesmentId = x.Key.AssesmentId
});
英文:
var data = from list in _context.LearnerAssessments
           group list by new
    {
        list.Learner,
        list.AssesmentId
    }
    into g
    select new
    {
        g.Key.Learner,
        g.Key.AssesmentId,
        Max= g.Max(x=>x.Attempt)
    };

or using fluent API :

var data = _context.LearnerAssessments.GroupBy(l => new { l.Learner, l.AssesmentId }, (keys, item) => new
{
    Key = keys,
    MaxAttemp = item.Max(x => x.Attempt)
}).Select(x => new LearnerAssessment
{
    Learner = x.Key.Learner,
    Attempt = x.MaxAttemp,
    AssesmentId = x.Key.AssesmentId

});

huangapple
  • 本文由 发表于 2023年2月18日 14:45:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定