Remove multiple items by value from dropdownlist C

2019-07-04 06:14发布

问题:

I have one dropdownlist named drpdemo and consist some listitems as shown below

Design Code:

<asp:DropDownList ID="drpdemo" runat="server">
    <asp:ListItem Value="213">Select</asp:ListItem>
    <asp:ListItem Value="0">0</asp:ListItem>
    <asp:ListItem Value="2">2</asp:ListItem>
    <asp:ListItem Value="3">3</asp:ListItem>
    <asp:ListItem Value="4">4</asp:ListItem>
    <asp:ListItem Value="5">5</asp:ListItem>
    <asp:ListItem Value="0">0</asp:ListItem>
</asp:DropDownList>

Inline Code:

protected void Page_Load(object sender, EventArgs e)
{
    drpdemo.Items.Remove(drpdemo.Items.FindByValue("0"));
}

Current Output:

Select
  2
  3
  4
  5
  0

Above output comes with the 0, which i don't want it in output.

Expected Output:

Select
   2
   3
   4
   5

Note: Dont want to use any loop.

回答1:

You'll have to use a loop because Remove takes one ListItem and FindByValue returns only one ListItem.

To get the items to delete, we can do:

var toDelete = drpDemo.Items
               .Cast<ListItem>()
               .Where(i => i.Value == "0");

Then you can do:

foreach (var item in toDelete)
{
    drpDemo.Items.Remove(item);
}

Or if you're functionally inclined, do:

toDelete.ForEach(i => drpDemo.Items.Remove(i));

And all in one:

drpDemo.Items
    .Cast<ListItem>()
    .Where(i => i.Value == "0")
    .ToList()
    .ForEach(i => drpDemo.Items.Remove(i));


回答2:

Dropdown list does not support any method for removing multiple items at once so you will have to use a loop.

If you're ok with using a loop internally, but simply don't want to write one, you can always use LINQ (though I'll leave it for you to judge if it improves readability vs. using a loop).

drpdemo.Items
       .OfType<ListItem>()
       .Where(li => li.Value == "0")
       .ToList()
       .ForEach(li => drpdemo.Items.Remove(li));


回答3:

If you look carefully to your drop down list, you will notice that there are two items with the same value, 0. So the method FindByValue finds the first and then you remove only this. If you had only one ListItem with value 0, then you wouldn't have seen it.