Split a list into multiple lists at increasing sequence broken

前端 未结 9 1118
不知归路
不知归路 2021-02-18 19:11

I\'ve a List of int and I want to create multiple List after splitting the original list when a lower or same number is found. Numbers are not in sorted order.<

9条回答
  •  再見小時候
    2021-02-18 19:58

    You can use the index to get the previous item and calculate the group id out of comparing the values. Then group on the group ids and get the values out:

    List data = new List { 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6 };
    
    int groupId = 0;
    var groups = data.Select
                     ( (item, index)
                       => new
                          { Item = item
                          , Group = index > 0 && item <= data[index - 1] ? ++groupId : groupId
                          }
                     );
    
    List> list = groups.GroupBy(g => g.Group)
                                 .Select(x => x.Select(y => y.Item).ToList())
                                 .ToList();
    

提交回复
热议问题