从下拉列表 C# 中按值删除多个项目

Remove multiple items by value from dropdownlist C#

我有一个名为 drpdemo 的下拉列表,其中包含一些列表项,如下所示

设计代码:

<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>

内联代码:

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

当前输出:

Select
  2
  3
  4
  5
  0

以上输出带有 0,我不希望它出现在输出中。

预期输出:

Select
   2
   3
   4
   5

Note: Dont want to use any loop.

如果仔细查看下拉列表,您会注意到有 两个 项具有 相同的值0。所以方法 FindByValue 找到第一个,然后你只删除这个。如果你只有一个 ListItem,值为 0,那么你就不会看到它了。

你必须使用循环,因为 Remove 需要一个 ListItemFindByValue returns 只需要一个 ListItem.

要获取要删除的项目,我们可以这样做:

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

那么你可以这样做:

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

或者,如果您有功能倾向,请执行以下操作:

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

合二为一:

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

Dropdown 列表不支持一次删除多个项目的任何方法,因此您必须使用循环。

如果您可以在内部使用循环,但只是不想编写循环,您可以随时使用 LINQ(尽管我会留给您判断它是否提高了可读性与使用循环)。

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