For example, we want to remove some selected items from a ListBox (similar in any collection object). In traditional code, it has to loop backward thro whole items
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
Benefit from LINQ greedy operator, the code can be simplified as following
foreach (ListItem item in ListBox1.Items.Cast<ListItem>().Where(i => i.Selected).ToList())
{
ListBox1.Items.Remove(item);
}
Here, greedy operator ToList() is important. Missing it will result in error.
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
Benefit from LINQ greedy operator, the code can be simplified as following
foreach (ListItem item in ListBox1.Items.Cast<ListItem>().Where(i => i.Selected).ToList())
{
ListBox1.Items.Remove(item);
}
Here, greedy operator ToList() is important. Missing it will result in error.