Search code examples
c#linqoptimizationwebformsprojection

Is there a simpler way to preform projection on a ListItemCollection?


G'day all, Is there a way to preform projection on the contents of a list box. Specifically I'd like to be able to do it without having to clear and add back the contents of my listbox This is what I currently have.

public static void SetSelectedWhere(this ListBox listbox, Func<ListItem,bool> condition) 
{
   var queryableList = listbox.Items.Cast<ListItem>();
   queryableList.Select(x=>condition(x)?x.Selected:x.Selected=false);
   listbox.Items.Clear();
   listbox.Items.AddRange(queryableList.ToArray<ListItem>());
}

and it seems silly to have to clear out my existing collection and add the contents back.

Any thoughts


Solution

  • What about plain old iteration?

    foreach (ListItem item in listbox.Items)
    {
        item.Selected = condition(item);
    }
    

    LINQ is not the answer to life the universe and everything. Particularly that part of the universe that involves setting properties on existing objects.