Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在单个列上分组数据并合并另一列_C#_Linq - Fatal编程技术网

C# 在单个列上分组数据并合并另一列

C# 在单个列上分组数据并合并另一列,c#,linq,C#,Linq,我有一组具有以下列的对象 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

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

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

我还添加了查询语法,我发现在这种情况下更具可读性,这很好。感谢这是一个无需单独选择
Select