Question Setting member values in a list.

capnyoaz

New member
Joined
Dec 7, 2008
Messages
4
Programming Experience
10+
Hello, I have a List(of AClass) that contains a few dozen items. I was wondering if there was an easy way to set the properties of all of the items in the list to a particular value, i.e.

MyList.SetAll(enabled, true)

Where something like this would set all of the items "enabled" property to true.
Is there some built in way to do this? Can I use Linq?
 
You can use the ForEach extension and call an Action delegate, but it is equally easy to just For Each the list with a regular loop.
 
When the next version of VB arrives it will support Subs as well as Functions as lambda expressions, so using the ForEach method will be a more attractive proposition. It would look something like this:
VB.NET:
myList.ForEach(New Action(Sub(ctl As Control) ctl.Enabled = True))
By the way, ForEach is not an extension method. It's a bona fide member of the List class.
 
ForEach is not an extension method. It's a bona fide member of the List class.
Ah yes, that one didn't have the down arrow in intellisense after all.
 
It's also worth noting that C# has had anonymous methods, which do support void functions (the C# equivalent of a VB Sub), since version 2.0:
VB.NET:
List<Control> controls = new List<Control>();

// ...

controls.ForEach(delegate(Control c) { c.Enabled = false; });
 
Back
Top