嗨,我想在有10乘10的地方换一个byte[]。这是我的代码。如果我的数据为“10 20 10 20 40 50 50 50 10 03”,我想用"10 20 10 20 50 50 50 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,
}
}
发布于 2015-09-11 07:31:28
无法插入数组(可以使用List<T>
进行插入),因此您必须创建一个新的数组;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)而不是使用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);
发布于 2015-09-11 07:47:40
它有助于将数组(IEnumerable<T>
in C#)这样的序列看作可以转换为新序列的东西。就像当你把数字转换成一个函数时,序列也可以被转换。
考虑一下是否有一个被定义为Add10If10(Byte b)
的函数。看起来可能是这样的:
public static Byte Add10If10(Byte b)
{
if (b == 10)
{
return b + 10;
}
return b;
}
进入这个位置的数字会根据条件进行转换,结果要么更大,要么相同。对序列也可以这样做,您可以获取一个具有一定数量的元素的序列,并对其进行转换,使其具有更多的元素。结果是一个新的序列:
public static IEnumerable<Byte> AddAdditional10If10(IEnumerable<Byte> values)
{
foreach (var b in values)
{
if (b == 10)
{
yield return 10;
}
yield return b;
}
}
该函数每遇到10个函数就会返回另外10个函数。既然有了正确的序列,就可以通过将其更改为数组来更改其存储方式:
AddAdditional10If10(addedbuffer).ToArray();
发布于 2015-09-11 07:56:44
这可以通过转换到字符串、使用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
s,它返回的序列为2 10
s:
byte[] res = source.SelectMany((b, index) => index == 0
|| index == source.Length - 1
|| b != 10 ?
Enumerable.Repeat(b, 1) : Enumerable.Repeat(b, 2))
.ToArray();
https://stackoverflow.com/questions/32517802
复制相似问题