如何在c#中移除选定的数组值
本文关键字:数组 | 更新日期: 2023-09-27 18:04:02
让我们考虑一个数组&它的值是
int[] array = {0, 0, 1, -1, -1,-1, 1, 1, 1};
我想删除数组的前三个值…?
,我的结果应该是array = {-1, -1, -1, 1, 1, 1}
提前感谢....!
你不能从数组中删除元素-它有固定的大小。
但是,您可以创建一个仅包含所需值的新数组。使用LINQ,这很容易:int[] newArray = array.Skip(3).ToArray();
如果您想修改现有的集合来添加或删除值,您需要List<T>
和它的RemoveRange
方法:
List<int> list = new List<int> {0, 0, 1, -1, -1,-1, 1, 1, 1};
list.RemoveRange(0, 3);
你不能调整数组的大小,所以你需要创建一个新的。您可以使用array.Skip(3).ToArray()
您可以使用一个简单的linq函数跳过第一个记录。
int[] array = { 0, 0, 1, -1, -1, -1, 1, 1, 1 };
int[] array2 = array.Skip(3).ToArray();
如果你有Linq,你可以这样做:
array = array.Skip(3).ToArray<int>();
这是一个从列表的方法来解决你的问题。我知道这是有点长,但我认为对于刚开始使用c#的人来说泛型也必须知道这类东西。
添加一个按钮到你的win-form,然后双击它并粘贴此代码到按F5或运行按钮
// define array or use your existing array
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// lets check the number of elements in array first
MessageBox.Show("Array has " + array.Length.ToString() + " elements only");
// creating list
List<int> myList = new List<int>();
// assigning array to list
myList = array.ToList();
// removing first 2 values from list
// first argument is the index where first item should remove
// second argument is how many items should remove
myList.RemoveRange(0, 3);
// testing our list
MessageBox.Show("List count is: "+ myList.Count.ToString());
string firstItem = myList[0].ToString();
MessageBox.Show("First Item if the list is :"+firstItem)
// now if you want you can convert MyList in to array again
array = myList.ToArray();
// if you debug and see you will see now the number of elements in array is 7
MessageBox.Show("New Array has " + array.Length.ToString() + " elements only");
***Best Regards and Happy Programming***