简体   繁体   English

将字节列表拆分为位置列表C#

[英]Splitting byte list into position lists C#

So I have a list of bytes 所以我有一个字节列表

List<byte> s = {1,2,3,2,2,2,3,1,2,4,2,1,4,.....};

I want to get new position lists using index of element.To something like this... 我想使用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

What`s the best way of doing this? 最好的方法是什么?

thank you. 谢谢。

You can use GroupBy and ToDictionary to get Dictionary<byte, List<int>> : 您可以使用GroupByToDictionary来获取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());

With LINQ, you can create an ILookup<TKey, TElement> with the desired results like this: 使用LINQ,可以创建具有所需结果的ILookup<TKey, TElement> ,如下所示:

var indicesByByte = s.Select((item, index) => new { Item = item, Index = index } )
                     .ToLookup(tuple => tuple.Item, tuple => tuple.Index);

Now, 现在,

  • indicesByByte[0] will be a sequence containing {0,7,11} indicesByByte[0]将是一个包含{0,7,11}的序列
  • indicesByByte[1] will be a sequence containing {1,3,4,5,8,10} indicesByByte[1]将是一个包含{1,3,4,5,8,10}的序列
  • etc. 等等

One way to do this is with LINQ, using the overload of Enumerable<T>.Select which contains the index, then grouping: 一种方法是使用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());

This will return a Dictionary<byte, List<int>> where the key is the value (1, 2, 3, 4, 5 in your example) and the value contains a list of positions. 这将返回Dictionary<byte, List<int>> ,其中键为值(在您的示例中为1、2、3、4、5),并且该值包含位置列表。


You could also do it using a for loop, in a single pass: 您也可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM