我想使用 linq 使用 value 对数据进行分组,并将相应的索引作为数组返回。
例子
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);
这将导致 aLookup<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() });