Skip to content

Instantly share code, notes, and snippets.

@wagonli
Created January 21, 2016 10:27
Show Gist options
  • Save wagonli/8bf0fb100a3b5568192e to your computer and use it in GitHub Desktop.
Save wagonli/8bf0fb100a3b5568192e to your computer and use it in GitHub Desktop.
int to loop extensions
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Wagonli.Tools
{
/// <summary>
/// Extensions to create for loop from an integer using the syntax
/// %int%.Times(the expression to execute)
/// </summary>
public static class LoopExtensions
{
/// <summary>
/// Execute loops time the actionExpression
/// </summary>
/// <param name="loops">the number of loop to execute the expression</param>
/// <param name="actionExpression"></param>
public static void Times(this int loops, Expression<Action<int>> actionExpression)
{
var action = actionExpression.Compile();
for (int i = 0; i < loops; i++)
{
action(i);
}
}
/// <summary>
/// execute loops time the funcExpression and return an instance of T for each loop.
/// </summary>
/// <typeparam name="T">the type of enumerable to return</typeparam>
/// <param name="loops">the "for" loop cardinality</param>
/// <param name="funcExpression"></param>
/// <returns></returns>
public static IEnumerable<T> Times<T>(this int loops, Expression<Func<int, T>> funcExpression)
{
var func = funcExpression.Compile();
for (int i = 0; i < loops; i++)
{
yield return func(i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment