![](/img/trans.png)
[英]C#: How can i store the values selected in checklistbox to an array
[英]How to remove selected array values in C#
讓我們考慮一個數組,它的值是
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#泛型的人們也必須知道這一點。
在您的獲勝表格中添加一個按鈕,然后雙擊它並將此代碼粘貼到命中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***
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.