将字节10替换为10 10

时间:2015-09-11 07:22:05

标签: c# sequence

嗨我想替换一个字节[],其中有10×10 10.这是我的代码。 如果我的数据是" 10 20 10 20 40 50 50 50 50 10 03"我想重复它 " 10 20 10 10 20 40 50 50 50 50 10 10 03" 注意:第一个字节不受影响 请按照我的评论,我的想法是将字节数组推到nxt位置并添加另外10个。

 foreach (var b in command.ToBytes()) 
                {

                   // var c = b;
                    transmitBuffer[count++] = b;  data is formed here
                    addedbuffer[addall++] = b;     duplication is made
                }
                if (addedbuffer[0] == 16 && addedbuffer[1] == 32 || addedbuffer[50] == 16 && addedbuffer[51] == 03)           /
                    {
/condition on which to enter here
                        addedbuffer[0] = 0;  //making 1st and 2nd value as null
                        addedbuffer[1] = 0;
                        for (int i = 0; i < addedbuffer.Length; i++) //till length i will chk 
                        {
                            if (addedbuffer[i] == 10) //replace 10  by 10 10 
                                addedbuffer[i] = 1010; // error,
                        }




        }

2 个答案:

答案 0 :(得分:4)

您无法 插入数组(您可以使用List<T>执行此操作),因此看起来您必须创建 new 数组; Linq解决方案:

  Byte[] source = new Byte[] {
    20, 10, 20, 40, 50, 50, 50, 50, 10, 03
  };

  var result = source
    .SelectMany((item, index) => 
       item == 10 && index != 0 ? new Byte[] { item, item } : new Byte[] { item })
    .ToArray();

但是,使用List<Byte>(仅为了插入10&#39;而不是Byte[]是更好的方法:

  List<Byte> list = List<Byte>() {
    20, 10, 20, 40, 50, 50, 50, 50, 10, 03
  };

  // In order not to read inserted 10's we loop backward 
  // i >= 1: 1st byte should be preserved as is even if its == 10
  for (int i = list.Count - 1; i >= 1; --i)
    if (list[i] == 10)
      list.Insert(i + 1, 10);

答案 1 :(得分:1)

这可以通过转换为字符串,使用String.Replace并转换回来:

byte[] source = new Byte[] { 20, 10, 20, 40, 50, 50, 50, 50, 10, 03 };

string[] strArr = Array.ConvertAll(source, b => b.ToString());
string[] replArr = String.Join(" ", strArr).Replace("10", "10 10").Split();

byte[] newArr = Array.ConvertAll(replArr, str => Byte.Parse(str));

编辑:

LINQ的另一种方法 - 在第一个和最后一个索引处的元素以及所有不等于10的元素都没有改变,对于所有剩余的10,它返回一个2 10的序列:

byte[] res = source.SelectMany((b, index) => index == 0 
                                             || index == source.Length - 1      
                                             || b != 10 ? 
                               Enumerable.Repeat(b, 1) : Enumerable.Repeat(b, 2))
                   .ToArray();