将排序列表分组而不影响linq中的排序

时间:2014-04-02 06:04:14

标签: c# linq sorting grouping

我有对象列表。我需要按属性进行排序,然后通过一组其他属性对结果进行分组,但这样做只是更改顺序并首先维护组。如果需要,我需要分组,同时保持排序。 我试过两种方式

  1. 简单订购和分组
  2.   

    model.OrderBy(o => o.OrderKey).GroupBy(o => new {o.Key1,o.Key2})

    1. 按订单列表(PLINQ)订购,然后再订购
    2.   

      model.OrderBy(o => o.OrderKey).AsParallel()。AsOrdered()。GroupBy(o => new {o.Key1,o.Key2})

      我的输入就像

      OrderKey Key1 Key2
      a        1    2
      b        1    2
      c        1    3
      d        1    2
      

      我希望输出像

      [
        [a, 1, 2],
        [b, 1, 2]
      ],
      [
       [c, 1, 3]
      ],
      [
       [d, 1, 2]
      ]
      

1 个答案:

答案 0 :(得分:2)

这可以使用每个项目的索引来解决,并添加一些逻辑以与之前的项目进行比较(除非索引为0):

// Example data
var list = new List<dynamic>{
            new {orderKey = "a", key1 = 1, key2 = 2},
            new {orderKey = "b", key1 = 1, key2 = 2},
            new {orderKey = "c", key1 = 1, key2 = 3},
            new {orderKey = "d", key1 = 1, key2 = 2}
    };

var groupNr = 0; // initial group

var sorted = 
        list
            .OrderBy(i => i.orderKey)
            // Create a new item for each, adding a calculated groupNr:
            .Select((i, nr) => 
                       new { 
                            i.orderKey, 
                            i.key1, 
                            i.key2, 
                            groupNr = (nr == 0 // check if first group
                                           ? 0 // first groupNr must be 0
                                           : (i.key1 == list[nr-1].key1 
                                                && i.key2 == list[nr-1].key2) 
                                              ? groupNr 
                                              : ++groupNr ) 
        })

     // Now just group by the groupNr we have added:
 .GroupBy(i => i.groupNr);

在LINQPad中对此进行测试会得到以下结果,您应该可以从中提取所需内容:

enter image description here