遇到这样一个问题,已经定义过且排好顺序的数组中(比如25个元素)指定位置再插入一个元素,
怎么实现这个??
删除呢???

解决方案 »

  1.   


    int[] arr = new int[26];
    拷贝指定位置之前的,插入元素,再拷贝指定位置之后的。。
      

  2.   

    估计得再new个数组,长度为原来的+1,然后将数据复制过去
      

  3.   

    建议使用以下泛型类:
    List<T>
    SortedList<TKey, TValue>
    Dictionary<TKey, TValue>如果需要自己用数组实现,可以考虑用二分查找,但增加或删除元素都必须放在新建立的数组中,因为.NET中数组长度是不可变的。
      

  4.   

    如果是数组。。那你重新创建数组 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);
              
             
      

  5.   

    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);
             }