LINQ从列表中的多个类似记录中选择最小字段值< T>

xdnvmnnf  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(102)

我试图弄清楚如何在T-SQL中将我所知道的作为一个组和聚合过程来做。
我有一个List<T>,在这个列表中,每个示例有2条记录。我需要价值较低的记录。
所以在申请中我有学生记录。所以我的列表应该是这样的:

0    studentid 1    score 75.345
1    studentid 1    score 33.653
2    studentid 2    score 94.876
3    studentid 2    score 15.234
etc....

我在List<Student>结果中有这些记录:

var result = abc.Find<Student>...snip

需要明确的是,业务规则要求找出两者之间的较低分数。
那么我如何在Linq中完成这种过滤和选择呢?我看到有Group和Aggregate Linq扩展,但老实说,我不确定这是否是我们要追求的路线。

3hvapo4f

3hvapo4f1#

使用GroupByMin函数。

var result = context.GroupBy(s=> s.StudentId)
                    .Select(sg => new {
                                        StudentId = sg.Key, 
                                        MinScore = sg.Min(sc=> sc.Score)
                                      });
axkjgtzd

axkjgtzd2#

也许这会有所帮助:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var s1=new Student(){Id=0, Name="Student 1", Score=56.44};
        var s2=new Student(){Id=1, Name="Student 1", Score=34.45};
        var s3=new Student(){Id=2, Name="Student 2", Score=56.23};
        var s4=new Student(){Id=3, Name="Student 2", Score=98.54};

    var list=new List<Student>(){s1,s2,s3,s4};

    var select=list.OrderBy(x=>x.Score).GroupBy(x=>x.Name);

    var newList=new List<Student>();

    foreach (var item in select){

        newList.Add(item.First());

    }

    foreach (var item in newList){

        Console.WriteLine(item.Id +"/"+item.Name +"/"+item.Score);
    }
}

public class Student
{
    public int Id {get;set;}
    public string Name {get;set;}
    public double Score {get;set;}
    }
  }

首先,你需要order by分数,然后group-by名称,然后从每个组中取first
dotnetfiddle

相关问题