Skip to content

Instantly share code, notes, and snippets.

@SplittyDev
Last active August 29, 2015 14:09
Show Gist options
  • Save SplittyDev/613dc34e264b8bf77ac7 to your computer and use it in GitHub Desktop.
Save SplittyDev/613dc34e264b8bf77ac7 to your computer and use it in GitHub Desktop.
Linq Extension Each
using System;
// Stable
namespace System.Linq
{
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public static class LinqExtensions
{
#region Each, LazyEach
/// <summary>
/// Lazy, chainable ForEach loop
/// </summary>
/// <returns>The each.</returns>
/// <param name="source">Source.</param>
/// <param name="action">Action.</param>
/// <typeparam name="TResult">The 1st type parameter.</typeparam>
public static IEnumerable<TResult> LazyEach<TResult> (this IEnumerable<TResult> source, Action<TResult> action)
{
foreach (var elem in source) {
action (elem);
yield return elem;
}
}
/// <summary>
/// Lazy, chainable ForEach loop with return value
/// </summary>
/// <returns>The each.</returns>
/// <param name="source">Source.</param>
/// <param name="action">Action.</param>
/// <typeparam name="TResult">The 1st type parameter.</typeparam>
public static IEnumerable<TResult> LazyEach<TResult> (this IEnumerable<TResult> source, Func<TResult, TResult> action)
{
foreach (var elem in source) {
yield return action (elem);
}
}
/// <summary>
/// Unchainable ForEach loop
/// </summary>
/// <param name="source">Source.</param>
/// <param name="action">Action.</param>
/// <typeparam name="TResult">The 1st type parameter.</typeparam>
public static IEnumerable<TResult> Each<TResult> (this IEnumerable<TResult> source, Action<TResult> action)
{
var actual = LazyEach (source, action);
return actual.Done ();
}
/// <summary>
/// Unchainable ForEach loop with return value
/// </summary>
/// <param name="source">Source.</param>
/// <param name="action">Action.</param>
/// <typeparam name="TResult">The 1st type parameter.</typeparam>
public static IEnumerable<TResult> Each<TResult> (this IEnumerable<TResult> source, Func<TResult, TResult> action)
{
var actual = LazyEach (source, action);
return actual.Done ();
}
#endregion
#region Done
/// <summary>
/// Evaluates a lazy chained operation.
/// Should be used at the very end of a Linq chain,
/// and only if the last extension in the chain is lazy
/// </summary>
/// <param name="source">Source.</param>
/// <typeparam name="TResult">The 1st type parameter.</typeparam>
public static IEnumerable<TResult> Done<TResult> (this IEnumerable<TResult> source)
{
foreach (var elem in source)
;
return source;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment