如何在C#中从数组中删除元素

本文关键字:数组 删除 元素 | 更新日期: 2023-09-27 18:29:54

所以我这里是我的代码:我有两个表单,-上一班的巴顿带你上二班。-表单2中包含Datagridview-您在表格1中输入信息(姓名、年龄),然后将它们加载到表格2中的数据网格视图中-当我从datagrid视图中选择要删除的行时,我希望该行也能从数组中删除。(我该怎么做)提前感谢

class Class1
{
   public struct client
    {
        public string nom;
        public string prenom;
        public int age;
    }
   public static client[] TC = new client[100];
   public static int i = 0;
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button3_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
    }
    private void btn_ajouter_Click(object sender, EventArgs e)
    {
        Class1.TC[Class1.i].nom = textBox_nom.Text;
        Class1.TC[Class1.i].prenom = textBox_prenom.Text;
        Class1.TC[Class1.i].age = int.Parse(textBox_age.Text);
        textBox_age.Clear();
        textBox_nom.Clear();
        textBox_prenom.Clear();
        Class1.i = Class1.i + 1;
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    private void btn_afficher_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Clear();
        for (int j = 0; j <= Class1.i-1; j++)
        {
            dataGridView1.Rows.Add(Class1.TC[j].nom,Class1.TC[j].prenom,Class1.TC[j].age);
        }
    }
    private void btn_supprimer_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
    }
}

如何在C#中从数组中删除元素

这里有一个从数组中删除项的扩展方法:

public static T[] RemoveAt<T> (this T[] arr, int index) {
    return arr.Where ((e, i) => i != index).ToArray ();
}

由于数组在C#中是不可变的,因此实际上不能从数组中移除元素。扩展方法返回一个新数组,其中删除了指定的元素,因此应该这样调用它:myarr = myarr.RemoveAt (index);

不能从数组中"移除",数组的大小是固定的。你创建了一个由100个客户端组成的数组,总会有100个客户端,你应该使用List,并使用它上的add/remove方法来更改它的元素。

您可以创建与数组相同的新列表,如

var yourList = yourArray.ToList();
yourList.Remove(someValue)
// to remove a specific value from your array
 yourList.RemoveAt(someIndex)
// to remove value from specific index.