如何获得"日期"最大/最小分数与(名称,课程)组使用Linq

时间:2015-10-22 05:23:44

标签: c# linq ado.net

数据表有4列

Name  Course    Date    Score
Alex  Math      10/15   90
Bob   Chem      10/28   91
Alex  Math      10/29   91
Alex  Math      12/08   89
Bob   Chem      11/23   97
Alex  Chem      10/16   94
Alex  Chem      10/30   92
Bob   Chem      10/01   94

我可以获得每个相应(名称,课程)组的所有最高分数,最低分数和平均分数,但是我如何获得并输出" Max_Date"和#34; Min_Date"相应的最大/最小分数项目?比如

Name  Course    Max_Date    Max    Min_Date   Min   Average
Alex  Math      10/29       91     12/08      89    90
Alex  Chem      10/16       94     10/30      92    93
Bob   Chem      11/23       97     10/28      91    94

以下是我的代码,如何获取日期项?

var result = dt.AsEnumerable()
           .GroupBy(r => new
           {
               name = r.Field<string>("Name"),
               course = r.Field<string>("Course")
           })
           .Select(g => new
           {
               name = g.Key.name,
               course = g.Key.course,
               max = g.Max(r => r.Field<int>("score")),
               min = g.Min(r => r.Field<int>("score")),
               ave = g.Average(r => r.Field<int>("score"))
           }).Distinct().ToList();
foreach (var item in result)
Console.WriteLine(s.name + "\t" + s.course + "\t" + s.max + "\t" + s.min + "\t" + (int)s.ave);

2 个答案:

答案 0 :(得分:0)

这样的事情:

dt.AsEnumerable()
.GroupBy(r => new
{
   name = r.Field<string>("Name"),
   course = r.Field<string>("Course")
})
.Select(g => new {
    Group = g,
    MaxEntry = g.First(gg => gg.Field<int>("score") == g.Max(r => r.Field<int>("score")))
})
.Select(g => new
{
   name = g.Group.Key.name,
   course = g.Group.Key.course,
   max = g.MaxEntry.Field<int>("score"),
   maxdate = g.MaxEntry.Field<datetime>("date"),
   min = g.Group.Min(r => r.Field<int>("score")),
   ave = g.Group.Average(r => r.Field<int>("score"))
}).Distinct().ToList();

注意:未经测试,但应该给你一个想法

答案 1 :(得分:0)

var result = dt.AsEnumerable()
           .GroupBy(r => new
           {
               name = r.Field<string>("Name"),
               course = r.Field<string>("Course")
           })
           .Select(g => new
           {
               name = g.Key.name,
               course = g.Key.course,
               max = g.Max(r => r.Field<int>("score")),
Max_Date    = g.FirstOrDefault(x=> x.Field<int>("score")==g.Max(r => r.Field<int>("score")).Date    ,
Min_Date= g.FirstOrDefault(x=> x.Field<int>("score")==g.Min(r => r.Field<int>("score")).Date    ,
               min = g.Min(r => r.Field<int>("score")),
               ave = g.Average(r => r.Field<int>("score"))
           }).Distinct().ToList();
foreach (var item in result)
Console.WriteLine(s.name + "\t" + s.course + "\t" + s.max + "\t" + s.min + "\t" + (int)s.ave);