所以我有一个字节列表
List<byte> s = {1,2,3,2,2,2,3,1,2,4,2,1,4,.....};
我想使用元素索引来获取新的位置列表。就像这样......
List<byte> 1 = {0,7,11};
List<byte> 2 = {1,3,4,5,8,10};
List<byte> 3 = {2,6};
List<byte> 4 = {9,12};
List<byte> 5 = ..... and so on
这样做的最佳方法是什么?
谢谢。答案 0 :(得分:3)
您可以使用GroupBy
和ToDictionary
来获取Dictionary<byte, List<int>>
:
var dict = s.Select((value, index) => new { value, index })
.GroupBy(x => x.value)
.ToDictionary(g => g.Key, g => g.Select(x => x.index).ToList());
答案 1 :(得分:1)
使用LINQ,您可以创建具有所需结果的ILookup<TKey, TElement>
,如下所示:
var indicesByByte = s.Select((item, index) => new { Item = item, Index = index } )
.ToLookup(tuple => tuple.Item, tuple => tuple.Index);
现在,
indicesByByte[0]
将是包含{0,7,11}
indicesByByte[1]
将是包含{1,3,4,5,8,10}
答案 2 :(得分:0)
一种方法是使用LINQ,使用包含索引的Enumerable<T>.Select
重载,然后分组:
var groups = s.Select((item, index) => new {index, item})
.GroupBy(x => x.item, x => x.index)
.ToDictionary(x => x.Key, x => x.ToList());
这将返回Dictionary<byte, List<int>>
,其中键是值(示例中为1,2,3,4,5),值包含位置列表。
您也可以在一次传递中使用for循环来执行此操作:
var groups = new Dictionary<byte, List<int>>();
for (int i = 0; i < s.Count; i++)
{
if(!groups.ContainsKey(s[i]))
groups[s[i]] = new List<int>();
groups[s[i]].Add(i);
}