[英]removing items from listbox
在 Windows Forms 應用程序中,我有一個包含重復項目的列表框(例如,有項目:1,1,2,2,3,3,4,4)。 我正在使用此代碼刪除所有其他項目:
for (int i = 0; i < ItemsCount/2; i++)
{
listBox1.Items.Remove(listBox1.Items[ItemsCount - 2 * i - 1]);
}
它刪除索引號為 7、5、3 和 1 的項目。結果是包含項目的列表框:1、2、3、4。 到現在為止一切正常。
但是,當列表框有項目:1,1,2,2,1,1,2,2 時,結果應該是列表框:1,2,1,2。 問題是,結果是 1,1,2,2。 你知道問題出在哪里嗎?
可能讓您感到困惑的是Remove
方法接收要刪除的項目的值,然后刪除它的第一次出現。
相反,如果您想刪除特定索引處的項目,則應改用RemoveAt
方法,該方法采用要刪除的項目的索引:
for (int i = 0; i < ItemsCount/2; i++)
{
listBox1.Items.RemoveAt(ItemsCount - 2 * i - 1);
}
因為你問為什么會這樣,在你的第一個例子中,你刪除了重復項,因為任何數字的唯一實例都彼此相鄰,所以看起來所有其他項目都被刪除了。
然而,在第二個示例中,情況並非如此。 這是發生了什么:
ItemsCount = 8
Starting values: {1,1,2,2,1,1,2,2}
i = 0
Remove [ItemsCount - 2 * i - 1] = [8 - 2 * 0 - 1] = [7]
The item at index 7 is '2', so we remove the first '2'
New values: {1,1,2,1,1,2,2}
i = 1
Remove [ItemsCount - 2 * i - 1] = [8 - 2 * 1 - 1] = [5]
The item at index 5 is '2', so we remove the first '2'
New values: {1,1,1,1,2,2}
i = 2
Remove [ItemsCount - 2 * i - 1] = [8 - 2 * 2 - 1] = [3]
The item at index 3 is '1', so we remove the first '1'
New values: {1,1,1,2,2}
i = 3
Remove [ItemsCount - 2 * i - 1] = [8 - 2 * 2 - 1] = [1]
The item at index 1 is '1', so we remove the first '1'
Ending values: {1,1,2,2}
您可以對數組中的所有奇數或偶數索引元素使用模數運算符 select,如下所示。
public static void Main()
{
//var items = new List<int>(){1,1,2,2,3,3,4,4};
var items = new List<int>(){1,1,2,2,1,1,2,2};
// select all elements at the odd index of an array. To get the even indexed item, use 'index % 2 == 0'
var updatedItems = items.Where((item, index) => index % 2 != 0);
Console.WriteLine(string.Join(',', updatedItems));
}
使用此Fiddle進行實驗。
或者更適合您的場景:
listBox1.Items = listBox1.Items.Where((item, index) => index % 2 != 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.