C#实现向数组指定索引位置插入新的元素值

 更新时间:2024年02月07日 10:48:22   作者:wenchm  
这篇文章给大家介绍了利用C#实现向数组指定索引位置插入新的元素值,首先需要定义一个一维数组,然后修改数组的长度,从而在其中增加一个元素,需要的朋友可以参考下

一、使用的方法

1.自定义插入方法 

首先需要定义一个一维数组,然后修改数组的长度(这里使用Length属性获取数组的长度,然后加1,作为新数组的长度),从而在其中增加一个元素。只有增加了数组的长度以后才能在这个数组中增加新的元素。

2.使用List<T>.Add(T) 方法

首先,创建一个与原始数组大小相同的动态数组(例如,List<T>)。然后,将原始数组的元素复制到动态数组中,直到到达要插入元素的索引位置。在动态数组中插入新元素。将原始数组中剩余的元素复制到动态数组中。最后,将动态数组转换回数组并返回。

二、实例

1.示例1:List<T>.Add(T) 方法

// 将一个元素插入到现有数组的指定索引位置,
// 并将原来位于该位置的元素向后移动
 
namespace _095_1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
 
            int[] originalArray = [1, 2, 3, 4, 5];
            int elementToInsert = 10;
            int indexToInsert = 2;
 
            int[] newArray = InsertElement(originalArray, elementToInsert, indexToInsert);
 
            Console.WriteLine(string.Join(", ", newArray));
        }
 
        static int[] InsertElement(int[] originalArray, int elementToInsert, int indexToInsert)
        {
            List<int> dynamicArray = new(originalArray.Length);
 
            // Copy elements from original array to dynamic array until the insertion index
            for (int i = 0; i < indexToInsert; i++)
            {
                dynamicArray.Add(originalArray[i]);
            }
 
            // Insert the element at the specified index
            dynamicArray.Add(elementToInsert);
 
            // Copy remaining elements from original array to dynamic array
            for (int i = indexToInsert; i < originalArray.Length; i++)
            {
                dynamicArray.Add(originalArray[i]);
            }
 
            // Convert dynamic array to a new array and return
            return [.. dynamicArray];
        }
    }
}
//运行结果:
/*
1, 2, 10, 3, 4, 5
 */

2.示例:自定义插入方法

//在既有数组中的指定位置插入一个新的元素,
//并遍历输出新数组
namespace _095
{
    public partial class Form1 : Form
    {
        private Button? button1;
        private Button? button2;
        private Label? label1;
        private Label? label2;
        private TextBox? textBox1;
        private TextBox? textBox2;
        private RichTextBox? richTextBox1;
        private Label? label3;
        private TextBox? textBox3;
        private int[] int_array = new int[8];
 
        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Load += Form1_Load;
        }
 
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(12, 9),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 0,
                Text = "生成数组",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(224, 36),
                Name = "button2",
                Size = new Size(43, 23),
                TabIndex = 1,
                Text = "确定",
                UseVisualStyleBackColor = true
            };            
            button2.Click += Button2_Click;
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 42),
                Name = "label1",
                Size = new Size(56, 17),
                TabIndex = 2,
                Text = "插入索引"
            };
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 69),
                Name = "label2",
                Size = new Size(56, 17),
                TabIndex = 3,
                Text = "新数组:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(93, 9),
                Name = "textBox1",
                Size = new Size(174, 23),
                TabIndex = 4
            };
            // 
            // textBox2
            // 
            textBox2 = new TextBox
            {
                Location = new Point(73, 36),
                Name = "textBox2",
                Size = new Size(40, 23),
                TabIndex = 5
            };          
            // 
            // richTextBox1
            // 
            richTextBox1 = new RichTextBox
            {
                Location = new Point(12, 90),
                Name = "richTextBox1",
                Size = new Size(254, 44),
                TabIndex = 6,
                Text = ""
            };
            // 
            // label3
            // 
            label3 = new Label
            {
                AutoSize = true,
                Location = new Point(118, 42),
                Name = "label3",
                Size = new Size(56, 17),
                TabIndex = 7,
                Text = "插入元素"
            };
            // 
            // textBox3
            // 
            textBox3 = new TextBox
            {
                Location = new Point(179, 36),
                Name = "textBox3",
                Size = new Size(40, 23),
                TabIndex = 8
            };
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(279, 146);
            Controls.Add(textBox3);
            Controls.Add(label3);
            Controls.Add(richTextBox1);
            Controls.Add(textBox2);
            Controls.Add(textBox1);
            Controls.Add(label2);
            Controls.Add(label1);
            Controls.Add(button2);
            Controls.Add(button1);
            Name = "Form1";
            Text = "在数组中添加一个元素";
 
        }
        /// <summary>
        /// 生成数组事件
        /// 遍历生成整形数组,并遍历输出
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            textBox1!.Clear();
            for (int i = 0; i < int_array.GetUpperBound(0) + 1; i++)
            {
                int_array[i] = i;
            }
            for (int i = 0; i < int_array.GetUpperBound(0) + 1; i++)
            {
                textBox1.Text += int_array[i] + " ";
            }
        }
        /// <summary>
        /// 确定插入事件
        /// 在生成的数组索引=4的位置插入一个元素,并遍历输出
        /// 这个事件不仅调用AddArray方法,更是在调用该方法之后改变了数组的大小
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {
            richTextBox1!.Clear();
            if ((textBox2!.Text != "")&& (textBox3!.Text !="")&& (textBox3!.Text.Length == 1))
            {
                int_array = AddArray(int_array, Convert.ToInt32(textBox2!.Text), Convert.ToInt32(textBox3!.Text));
 
                for (int i = 0; i < int_array.GetUpperBound(0) + 1; i++)
                {
                    richTextBox1.Text += int_array[i] + " ";
                }
            }
            else
            {
                MessageBox.Show("输入信息不能为空且元素长度恒为1", "提示");
            }
        }
 
        /// <summary>
        /// 向数组中插入单个元素的方法
        /// </summary>
        /// <param name="ArrayBorn">要向其中添加元素的一维数组</param>
        /// <param name="Index">添加索引</param>
        /// <param name="Value">添加值</param>
        /// <returns></returns>
        static int[] AddArray(int[] ArrayBorn, int Index, int Value)
        {
            if (Index >= ArrayBorn.Length)
                Index = ArrayBorn.Length - 1;
            int[] TemArray = new int[ArrayBorn.Length + 1];//声明一个新的数组
            for (int i = 0; i < TemArray.Length; i++)
            {
                if (Index >= 0)
                {
                    if (i < (Index + 1))        //判断遍历到的索引是否小于添加索引加1
                        TemArray[i] = ArrayBorn[i];
                    else if (i == (Index + 1))//判断遍历到的索引是否等于添加索引加1
                        TemArray[i] = Value;
                    else
                        TemArray[i] = ArrayBorn[i - 1];
                }
                else
                {
                    if (i == 0)//数组首位置
                        TemArray[i] = Value;
                    else
                        TemArray[i] = ArrayBorn[i - 1];
                }
            }
            return TemArray;
        }
    }
}

到此这篇关于C#实现向数组指定索引位置插入新的元素值的文章就介绍到这了,更多相关C#向数组插入元素值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#中的multipart/form-data提交文件和参数

    C#中的multipart/form-data提交文件和参数

    这篇文章主要介绍了C#中的multipart/form-data提交文件和参数,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • C#获取动态生成的CheckBox值

    C#获取动态生成的CheckBox值

    checkbox是VS2012的常用控件之一,可以方便的为某些功能取消或启用,下面教你如何简单使用checkbox。本文通过两种方法给大家介绍,需要的朋友一起看看吧
    2015-09-09
  • C#结合JS解决Word添加无效位图导致进程停滞的问题

    C#结合JS解决Word添加无效位图导致进程停滞的问题

    这篇文章主要为大家详细介绍了C#如何结合JS解决Word添加无效位图导致进程停滞的问题,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-11-11
  • C#委托与匿名委托详解

    C#委托与匿名委托详解

    这篇文章主要为大家详细介绍了C#委托与匿名委托的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • C#利用反射实现多数据库访问

    C#利用反射实现多数据库访问

    本文详细讲解了C#利用反射实现多数据库访问的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • c#使用EPPlus将图片流嵌入到Excel实现示例

    c#使用EPPlus将图片流嵌入到Excel实现示例

    这篇文章主要为大家介绍了c#使用EPPlus将图片流嵌入到Excel实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • C#导出Excel的示例详解

    C#导出Excel的示例详解

    这篇文章主要为大家详细介绍了C#导出Excel的示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • C#模拟Http与Https请求框架类实例

    C#模拟Http与Https请求框架类实例

    这篇文章主要介绍了C#模拟Http与Https请求框架类,实例分析了处理http与https请求的方法与信息处理的技巧,需要的朋友可以参考下
    2014-12-12
  • C#实现高效读写Excel工作表

    C#实现高效读写Excel工作表

    Excel 是各行业数据管理的核心载体,广泛应用于财务统计、库存管理、报表生成等场景,本文主要介绍了C#如何借助免费库 Free Spire.XLS for .NET实现读写 Excel 工作表,有需要的可以了解下
    2025-10-10
  • C#中using的使用方式详解

    C#中using的使用方式详解

    这篇文章主要介绍了C#中using的使用方式方式详解,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06

最新评论