LoginSignup
0
0

More than 3 years have passed since last update.

C# 連番の数値をグループわけする方法

Last updated at Posted at 2020-06-03

概要

連番の数値をグループ化する際に嵌ったので自分用のメモとして残しておく。

以下のような配列形式の数値を連番を整形して
int [] number = { 1,2,3,6,9,10,15,16 }

以下のような形式で取得をしたい
1,2,3
6
9,10
15,16

実現方法

以下の方法で実現が可能です。

var number = { 1,2,3,6,9,10,15,16 };

// 配列の要素からインデックスの値を引いた値は同じになることを利用してグルーピングしています
var result = number.Select((x , index) => (x , index))
                   .GroupBy(n => n.x - n.index, n => n.x);
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0