我想使用linq使用值对数据进行分组,并将相应的索引作为数组返回.
例
int[] input = {0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,2,2,2,2}
Run Code Online (Sandbox Code Playgroud)
预期产出
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]}
Run Code Online (Sandbox Code Playgroud)
任何人都可以指导我吗?
你可以用这个:
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());
Run Code Online (Sandbox Code Playgroud)
这首先选择一个匿名类型来保存数组中的原始索引,然后按值进行分组,然后将分组结果转换为字典,每个组的键作为字典的键,并从相应组中的所有元素中索引被选中.
一个更短的方式是:
var output2 = input.Select((x, i) => new { Value=x, Index=i })
.ToLookup(x => x.Value, x => x.Index);
Run Code Online (Sandbox Code Playgroud)
这将导致a Lookup<int, int>在语义上与Dictionary<int, int[]>.
| 归档时间: |
|
| 查看次数: |
821 次 |
| 最近记录: |