More Extension Methods

Here are a couple more extension methods you may find useful:

Collection splitter:

Split a collection into a sequence of fixed-size groups:

/// <summary>
/// Splits the specified items into fixed-size groups.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="size">The group size.</param>
/// <returns>Returns collection of groups.</returns>
public static IEnumerable<IGrouping<int, T>> Split<T>( this IEnumerable<T> source, int size )
{
    var index = 0d;

    return source.GroupBy( v => (int)( ( index++ ) / size ) );
}

You could use it like this:

var items = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var chunks = items.Split( 5 );

“For” enumerator:

Generate a sequence of elements like a for loop:

/// <summary>
/// Generates a sequence of elements while <paramref name="predicate"/> is <see cref="true"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The initial value.</param>
/// <param name="predicate">A predicate to control continuation of the sequence.</param>
/// <param name="selector">A function to retrieve the next element.</param>
/// <returns>Returns a sequence of elements.</returns>
public static IEnumerable<T> For<T>( this T value, Predicate<T> predicate, Func<T, T> selector )
{
    while ( predicate != null && predicate( value ) )
    {
        yield return value;

        value = ( selector != null ) ? selector( value ) : default( T );
    }
}

It’s good for making non-enumerable sequences enumerable:

var pages = SiteMap.CurrentNode.For( n => n != null, n => n.ParentNode ).Reverse();

return string.Join( " > ", pages.Select( p => p.Title ).ToArray() );

Comments, suggestions and improvements always welcome!

2 Comments

Leave a comment