Is the ranged based for loop beneficial to performance?

The Standard is your friend, see [stmt.ranged]/1 For a range-based for statement of the form for ( for-range-declaration : expression ) statement let range-init be equivalent to the expression surrounded by parentheses ( expression ) and for a range-based for statement of the form for ( for-range-declaration : braced-init-list ) statement let range-init be equivalent … Read more

Intelligent way of removing items from a List while enumerating in C#

The best solution is usually to use the RemoveAll() method: myList.RemoveAll(x => x.SomeProp == “SomeValue”); Or, if you need certain elements removed: MyListType[] elems = new[] { elem1, elem2 }; myList.RemoveAll(x => elems.Contains(x)); This assume that your loop is solely intended for removal purposes, of course. If you do need to additional processing, then the … Read more

foreach with index [duplicate]

I keep this extension method around for this: public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action) { var i = 0; foreach (var e in ie) action(e, i++); } And use it like so: var strings = new List<string>(); strings.Each((str, n) => { // hooray }); Or to allow for break-like behaviour: public static … Read more

If Statement Against Dynamic Variable [duplicate]

Replace if (“state_$name” -eq “True”) { with: if ((Get-Variable -ValueOnly “state_$name”) -eq “True”) { That is, if your variable name is only known indirectly, via an expandable string, you cannot reference it directly (as you normally would with the $ sigil) – you need to obtain its value via Get-Variable, as shown above. However, as … Read more