Skip to content

Instantly share code, notes, and snippets.

@psuong
Last active September 19, 2019 01:54
Show Gist options
  • Save psuong/15807551aa0a8d98462b486253007ebc to your computer and use it in GitHub Desktop.
Save psuong/15807551aa0a8d98462b486253007ebc to your computer and use it in GitHub Desktop.
ForEachExtension methods for more expressive code
// Loop Extensions, but will generate garbage because we'd have to use lambda expressions
public static class LoopExtensions {
// Ex: (2, 5).ForEach(i => { --do some-action-on-this-elem-- }
public static void ForEach(this (int, int) range, Action<int> action)
{
for (int i = range.Item1; i < range.Item2; i++)
{
action(i);
}
}
// (50).Repeat(() => { --do-some-repeated-action-n-times-- })
public static void Repeat(this uint range, Action action) {
for (int i = 0; i < range; i++)
{
action();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment