简体   繁体   English

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

[英]Group a sorted list without affecting the sorting in linq

I have list of objects. 我有对象列表。 I need sorting by a property and then group the result by a set of other properties, but doing it simply changes the ordering and maintains the group first. 我需要按属性进行排序,然后通过一组其他属性对结果进行分组,但这样做只是更改顺序并首先维护组。 i need separation of group if needed while maintaining sorting. 如果需要,我需要分组,同时保持排序。 I tried two ways 我试过两种方法

  1. Simple Ordering and Grouping 简单的订购和分组

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

  1. Order as Ordered List (PLINQ) then Group 按订单列表(PLINQ)订购然后再订购

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

My Input would be like 我的输入就像

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

I expect the output to be like 我希望输出就像

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

This can be solved using the index of each item, and adding some logic to compare to the previous item (unless index is 0): 这可以使用每个项的索引来解决,并添加一些逻辑以与前一项进行比较(除非index为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);

Testing this in LINQPad gives the following result, from which you should be able to extract what you need: 在LINQPad中进行测试会得到以下结果,您应该可以从中提取所需内容:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM