[英]Splitting byte list into position lists C#
所以我有一个字节列表
List<byte> s = {1,2,3,2,2,2,3,1,2,4,2,1,4,.....};
我想使用element的索引获取新的职位列表。
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
最好的方法是什么?
谢谢。
您可以使用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());
使用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}
的序列 一种方法是使用LINQ,使用Enumerable<T>.Select
的重载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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.