求助:数组中插入和删除元素。。。 遇到这样一个问题,已经定义过且排好顺序的数组中(比如25个元素)指定位置再插入一个元素,怎么实现这个??删除呢??? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 int[] arr = new int[26];拷贝指定位置之前的,插入元素,再拷贝指定位置之后的。。 估计得再new个数组,长度为原来的+1,然后将数据复制过去 建议使用以下泛型类:List<T>SortedList<TKey, TValue>Dictionary<TKey, TValue>如果需要自己用数组实现,可以考虑用二分查找,但增加或删除元素都必须放在新建立的数组中,因为.NET中数组长度是不可变的。 如果是数组。。那你重新创建数组 byte[] _ArrayBytes = new byte[2]; _ArrayBytes[0]=1; _ArrayBytes[1]=3; byte[] _NewArrayBytes = new byte[_ArrayBytes.Length + 1]; int _Index =1; Array.Copy(_ArrayBytes, 0, _NewArrayBytes, 0, _Index); _NewArrayBytes[_Index] = 2; Array.Copy(_ArrayBytes, _Index, _NewArrayBytes, _Index+1, _ArrayBytes.Length - _Index); Example: public static void InsertElement(ref Int32[] arr, Int32 index, Int32 val) { if (index > arr.Length) return; Int32[] temp = arr; arr = new Int32[arr.Length + 1]; Int32 j = 0; for (Int32 i = 0; i < arr.Length; i++) { if (i != index) { arr[i] = temp[j]; j++; } else { arr[i] = val; } } } static void Main(string[] args) { Int32 [] arr = new Int32[]{1,2,3,4,5}; InsertElement(ref arr,3,10); foreach (Int32 i in arr) Console.WriteLine(i); } 点击左边按钮 右边Panel变化 两层循环取指定行有效数据,取不够行了怎么办? 请教一个正则表达式的写法:不含有单引号"'"的字符串~ 如何用winform发送/接收邮件 有那位大虾可以给我个技术文档,是关于用C#怎样调用485总线的IC读卡器的函数的全过程!!!!!!! 关于用线程读取串口数据 如何使用正则表达式匹配非特定字串? 想请问毕业在职的研究生大哥大姐们一个问题? 如何调用系统出错时候的报警声音。 使用CDO.Message对象发送邮件时附件会掉失? c#中如何实现编辑flash的图片、声音、背景等相关信息 求个简单的正则表达式
int[] arr = new int[26];
拷贝指定位置之前的,插入元素,再拷贝指定位置之后的。。
List<T>
SortedList<TKey, TValue>
Dictionary<TKey, TValue>如果需要自己用数组实现,可以考虑用二分查找,但增加或删除元素都必须放在新建立的数组中,因为.NET中数组长度是不可变的。
_ArrayBytes[1]=3;
byte[] _NewArrayBytes = new byte[_ArrayBytes.Length + 1]; int _Index =1; Array.Copy(_ArrayBytes, 0, _NewArrayBytes, 0, _Index); _NewArrayBytes[_Index] = 2; Array.Copy(_ArrayBytes, _Index, _NewArrayBytes, _Index+1, _ArrayBytes.Length - _Index);
{
if (index > arr.Length)
return;
Int32[] temp = arr;
arr = new Int32[arr.Length + 1];
Int32 j = 0;
for (Int32 i = 0; i < arr.Length; i++)
{
if (i != index)
{
arr[i] = temp[j];
j++;
}
else
{
arr[i] = val;
}
}
} static void Main(string[] args)
{ Int32 [] arr = new Int32[]{1,2,3,4,5};
InsertElement(ref arr,3,10);
foreach (Int32 i in arr)
Console.WriteLine(i);
}