Groupby和selectMany和orderby没有带回我需要的数据

时间:2015-11-03 11:00:25

标签: c#

我有两个List row1和row2.This是row1的数据:enter image description here

和第2行的数据:enter image description here

我将这两个列表连接成一个:

 var rows = rows1.Concat(rows2).ToList();

结果如下:enter image description here 然后想要在几个字段上进行groupBy并与其他字段一起排序。并对某些数据进行一些更改。这是我的代码

  var results = rows.GroupBy(row => new { row.FromBayPanel, row.TagNo })
                    .SelectMany(g => g.OrderBy(row => row.RowNo)
                    .Select((x, i) =>
                        new
                        {
                          TagGroup = x.TagGroup,
                          RowNo = (i == 0) ? (j++).ToString() : "",
                          TagNo = (i == 0) ? x.TagNo.ToString() : "",
                          FromBayPanel = x.FromBayPanel,                                                                           
                          totalItem = x.totalItem
                        }).ToList());

让我回到了这个结果:enter image description here

这不是我真正想要的结果。我想要所有相同的数据" FromBayPanel"一起上市。 我的代码中哪一部分错了?

1 个答案:

答案 0 :(得分:0)

我认为,当您想要在群组中订购元素时,您必须使用不同的方法,因为SelectMany只会将您的分组项目展平为一个列表。因此,您可以使用此代替rows.GroupBy(row => new { row.FromBayPanel, row.TagNo }).SelectMany(g => g.OrderBy(row => row.RowNo)

rows.OrderBy(x => x.FromBayPanel).ThenBy(x => x.TagNo) // this preserves the actual group-condition
         .ThenBy(x => x.RowNo) // here you order the items of every item within the group by its RowNo
         .GroupBy(row => new { row.FromBayPanel, row.TagNo })
         .Select(...)

编辑:您必须在每个组中选择WITHIN,而不是之后:

rows.GroupBy(row => new { row.FromBayPanel, row.TagNo })
         .ToDictionary(x => x.Key, 
             x => x.OrderBy(y => y.RowNo)
                 .Select((y, i) =>
                 new
                 {
                     TagGroup = y.TagGroup,
                     RowNo = (i == 0) ? (j++).ToString() : "",
                     TagNo = (i == 0) ? y.TagNo.ToString() : "",
                     FromBayPanel = x.FromBayPanel,                                                              
                     totalItem = y.totalItem
                 })
         )

编辑:测试见here