Reputation: 11
In Windows Forms Application I have a listbox with duplicated items (for example there are items: 1,1,2,2,3,3,4,4). I am removing every other item using this code:
for (int i = 0; i < ItemsCount/2; i++)
{
listBox1.Items.Remove(listBox1.Items[ItemsCount - 2 * i - 1]);
}
It removes items with index number 7,5,3 and 1. The result is listbox with items: 1,2,3,4. Until now everything works.
However, when the listbox has items: 1,1,2,2,1,1,2,2, the result should be listbox: 1,2,1,2. The problem is, that the result is 1,1,2,2. Do you have any idea what is the problem?
Upvotes: 1
Views: 588
Reputation: 645
You could use the modulus operator to select all odd or even indexed elements in an array, like this.
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));
}
Use this Fiddle to experiment.
Or more tailored to your scenario:
listBox1.Items = listBox1.Items.Where((item, index) => index % 2 != 0);
Upvotes: 0
Reputation: 37070
Probably what's confusing you is that the Remove
method takes in the value of an item to remove, and then it removes the first occurrence of it.
Instead, if you want to remove the item at a specific index, then you should use the RemoveAt
method instead, which takes the index of the item to remove:
for (int i = 0; i < ItemsCount/2; i++)
{
listBox1.Items.RemoveAt(ItemsCount - 2 * i - 1);
}
And because you asked why it was happening, in your first example, you get the duplicates removed because the only instances of any number are all next to each other, so it appears that every other item is being removed.
In the second example, however, that's not the case. Here's what happens:
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}
Upvotes: 2