对单个列上的数据进行分组,并合并另一个列

本文关键字:合并 另一个 单个列 数据 | 更新日期: 2023-09-27 17:49:25

我有一组具有以下列的对象

Id
ShiftStart
ShiftEnd

数据集示例

Id  ShiftStart  ShiftEnd
1   8.30        12.00
1   13.30       15.00
2   8.30        12.00
2   13.30       15.00
3   8.30        12.00

我想实现的是,

选择所有与id匹配的项目,然后合并移位数据。用逗号分隔

因此,一个final对象示例将包含以下数据

Id  ShiftStart    ShiftEnd
1   8.30, 13.30   12.00, 15.00    
2   8.30, 13.30   12.00, 15.00
3   8.30          12.00

对单个列上的数据进行分组,并合并另一个列

按Id分组,然后将每组内的所有时间连接在一起:

var groupedData
  = yourList.GroupBy(x => x.Id)
            .Select(g => new { Id = g.Key,
                               ShiftStartTimes = string.Join(", ", g.Select(x => x.ShiftStart))
                               ShiftEndTimes = string.Join(", ", g.Select(x => x.ShiftEnd)) });

查询语法:

var groupedData =
    from x in yourList
    group x by x.Id into g
    select new {
       Id = g.Key,
       ShiftStartTimes = String.Join(", ", g.Select(x => x.ShiftStart)),
       ShiftEndTimes = String.Join(", ", g.Select(x => x.ShiftEnd))
   };