pencilCake
pencilCake

Reputation: 53243

How can I remove all ListItems except the one having a particular value from an ItemList of a drop-down?

I have a dropdown : myDropDown.

And I need to remove all ListItem in its item collection which does not have a value equals to '-1' ?

myDropDown.Items. ... // TODO: Remove all ListItems that has a value different than '-1'

I don't want to create a loop etc.

How can I achieve this in a most self-documenting way? I assume with a LINQ statement.

Thanks

Upvotes: 1

Views: 4057

Answers (2)

Stefan
Stefan

Reputation: 14880

Assuming you are working with a System.Web.UI.WebControls.DropDownList, I think the good old for loop is the best choice here:

for (int i = d.Items.Count - 1; i >= 0; i--)
{
  if (d.Items[i].Value != "-1") d.Items.RemoveAt(i);
}

Upvotes: 2

Kevin Holditch
Kevin Holditch

Reputation: 5303

myDropDown.Items = myDropDown.Items.Where(x => x.value != -1);

Upvotes: 2

Related Questions