Linq 按多列对记录进行分组,然后选择第一条或默认记录

本文关键字:记录 选择 然后 默认 一条 Linq | 更新日期: 2023-09-27 17:56:08

我正在尝试按多列对表记录进行分组,并尝试获取组的第一行记录。下面是 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属性。

Linq 按多列对记录进行分组,然后选择第一条或默认记录

使用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;
你可以

尝试这两个LINQ查询,第一个获取每个给定组的第一个上传元素的简单集合,第二个获取所有上传组,每个只有排序列表的第一个上传。

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();