linq を使用して、値を使用してデータをグループ化し、対応するインデックスを配列として返したいと思います。
例
int[] input = {0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,2,2,2,2}
期待される出力
Dictionary<int,int[]> ouput = {0->[0,1,2,3,8,9,10,11]; 1 -> [4,5,6,7,12,13,14,15]; 2 -> [16,17,18,19]}
誰でも私を案内できますか?
これを使用できます:
var output = input.Select((x, i) => new { Value=x, Index=i })
.GroupBy(x => x.Value)
.ToDictionary(x => x.Key, x => x.Select(y => y.Index)
.ToArray());
これは、最初に匿名型を選択して元のインデックスを配列に保存し、次に値でグループ化し、その後、グループ化された結果を各グループのキーをディクショナリのキーとしてディクショナリに変換し、対応するグループ内のすべての要素からインデックスが選択されます。
より短い方法は次のとおりです。
var output2 = input.Select((x, i) => new { Value=x, Index=i })
.ToLookup(x => x.Value, x => x.Index);
これは、Lookup<int, int>
意味的に と同じ になりDictionary<int, int[]>
ます。
var result = input
.Select((i, index) => new{Num=i, Index=index})
.GroupBy(x => x.Num)
.ToDictionary(grp => grp.Key, grp => grp.Select(x => x.Index).ToArray());
試す
input.Select( (i, index) => new {Value = i, Index = index})
.GroupBy(x => x.Value).Select(y => new { Key = y.Key, Indexes = y.Select(z => z.Index).ToList() });