Remove multiple items by value from dropdown c #

I have one dropdownlist named drpdemo and made up of some lists like below.

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

      

Internal code:

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

      

Current output:

Select
  2
  3
  4
  5
  0

      

The above output goes from 0, which I don't need in the output.

Expected Result:

Select
   2
   3
   4
   5

      

Note. Don't want to use any loop.

+3


source to share


3 answers


You will need to use a loop because it Remove

takes one ListItem

and FindByValue

only returns one ListItem

.

To remove items, we can:

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 are functionally configured, follow these steps:

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

      

+4


source


If you look closely at your drop-down list, you will notice that there are two elements with the same value , 0

. So the method FindByValue

finds the first one and then you only remove that. If you only had one ListItem

with a value 0

, you wouldn't see it.



+1


source


Dropdown

list does not support any method for removing multiple elements at the same time, so you will have to use a loop.

If you're fine with using a loop internally, but just don't want to write it, you can always use LINQ (although I'll leave that for you to judge if it improves readability or uses a loop).

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

      

+1


source







All Articles