Can I use linq to remove items from asp .net DropDownList.Items?
-
11-12-2019 - |
Question
As title says, is it possible to use LINQ to remove Items from a DropDownList's .Items where the Item is not equal to strings that I specify?
To put it another way - I have a list of strings, if an Item doesn't match any string in the list, it is removed.
NOTE: I know how to achieve this, I can do it with a foreach loop. That's fine - but I want to know if there's a LINQ alternative.
EDIT: I should say - the Item's .Text property matches any item in the list of strings.
EDIT: For those interested, this was my proposed 'foreach' way:
private void FilterDropDownChoices(List<String> permittedChoices)
{
foreach(ListItem item in ddlChoices.Items)
{
if (!permittedChoices.Contains(item.Text))
{
ddlChoices.Items.Remove(item);
}
}
}
Solution
ryanulit actually provided the best answer.
The problem is that the ListItemCollection implements only the IEnumerable interface. LINQ extensions works upon IEnumerable<T>. Hence, casting (IEnumerable) to (IEnumerable<T>) - you can now use LINQ.
So, to answer your question:
ddlChoices.Items
.Cast<ListItem>()
.Where(item => !permittedChoices.Contains(item.Text))
.ToList()
.ForEach(ddlChoices.Items.Remove);
You have to use ToList() or ToArray() or similar because you can't modify a collection while reading from it - ToList() copies the references to the selected items which then can be looped over and removed from the ListItemCollection.
While writing this I saw Matten's comment - He highlighted useful functionality of the ListItemCollection (being able to remove items by their text property) but got the question wrong. The requirement was: you are only allow to have 'permittedChoices' inside ddlChoices.Items. Matten's example removes the valid choices and leaving the invalid ones which is the opposite of what he asked.
OTHER TIPS
LINQ is a query language, it is not used to modify your data. what you can do, it query your list of items for the condition you like and than effect the collection by your self.
sample:
var relevant = from item in list.Items
where permittedChoices.Contains(item.ToString())
select item
and than you can clear the Items list and add only the relevant you want.
ddlChoices.Clear();
ddlChoices.AddRange(relevant.ToArray());
Just to use linq? Here you go :-)
private static void FilterDropDownChoices(List<String> permittedChoices)
{
ddlChoices.Items.Cast<ListItem>()
.Where(li => permittedChoices.Contains(li.Text))
.ToList()
.ForEach(ddlChoices.Items.Remove);
}