Linq按多列分组记录并选择第一个或默认记录

时间:2016-07-08 20:08:03

标签: c# sql-server entity-framework linq

我正在尝试按多列对我的表记录进行分组,并尝试将组记录到第一行记录。这是Linq查询。

var uploadAddedDate = from up in db.Uploads
                       where up.Url != null
                       orderby up.xxx, up.table1.TeamId
                       group up by new
                       {
                         up.AddedDate,
                         up.xxx,
                         up.table1.TeamId
                        } into upgrp
                        select upgrp;   

我想选择每个组的第一行AddedDate属性。

2 个答案:

答案 0 :(得分:0)

使用FirstOrDefault扩展方法:

var uploadAddedDate = from up in db.Uploads
                      where up.Url != null
                      orderby up.xxx, up.table1.TeamId
                      group up by new
                      {
                         up.AddedDate,
                         up.xxx,
                         up.table1.TeamId
                      } into upgrp
                      select upgrp.FirstOrDefault();

我现在不完全确定,但我认为在group by之后无法保证订购组,所以此查询可以完成这项工作:

var uploadAddedDate = from up in db.Uploads
                      where up.Url != null
                      group up by new
                      {
                         up.AddedDate,
                         up.xxx,
                         up.table1.TeamId
                      } into upgrp
                      select upgrp.OrderBy(e=>new{e.xxx, e.table1.TeamId}).FirstOrDefault();

更新

如果您只想选择一列(在这种情况下为AddedDate),您可以使用let子句,如下所示:

var uploadAddedDate = from up in db.Uploads
                      where up.Url != null
                      group up by new
                      {
                         up.AddedDate,
                         up.xxx,
                         up.table1.TeamId
                      } into upgrp
                      let first=upgrp.OrderBy(e=>new{e.xxx, e.table1.TeamId}).FirstOrDefault()
                      select first.AddedDate;

答案 1 :(得分:0)

你可以尝试这两个linq查询,第一个得到一个简单的uploads元素集合,它是每个给定组的第一个,第二个得到所有上传组,每个组中只有第一个上传的有序列表。

var uploadAddedDate = 
           (from up in db.Uploads
            where up.Url != null
            group up 
              by new{
                     up.AddedDate,
                     up.xxx,
                     up.table1.TeamId
                  } into upgrp
            select upgrp
           ).Select(upgrp => 
               upgrp.OrderBy(upelem => 
                 new { upelem.xxx, upelem.table1.TeamId})).First();  


var uploadAddedDateByGroup = 
           (from up in db.Uploads
            where up.Url != null
            group up 
              by new{
                     up.AddedDate,
                     up.xxx,
                     up.table1.TeamId
                  } into upgrp
            select upgrp
           ).OrderBy(upgrp => 
               upgrp.OrderBy(upelem => 
                 new { upelem.xxx, upelem.table1.TeamId})).First();