Skip to content

Instantly share code, notes, and snippets.

@yngwie74
Created May 18, 2015 22:45
Show Gist options
  • Save yngwie74/f2a21432b1d76c94d62f to your computer and use it in GitHub Desktop.
Save yngwie74/f2a21432b1d76c94d62f to your computer and use it in GitHub Desktop.
Miscellaneous helper functions to work with Enumerations
public static class IterTools
{
private static readonly Random Random = new Random();
/// <summary>
/// Make an enumeration with a single element.
/// </summary>
/// <typeparam name="T">The type of the enumeration elements.</typeparam>
/// <param name="element">The single element to enumerate.</param>
/// <returns>A reference to the enumeration.</returns>
public static IEnumerable<T> ToAtom<T>(this T element)
{
yield return element;
}
/// <summary>
/// Splits an enumeration into fixed length partitions.
/// </summary>
/// <typeparam name="T">The enumeration type.</typeparam>
/// <param name="source">The source enumeration.</param>
/// <param name="size">The maximum size of each partition.</param>
/// <returns>A reference to the enumeration.</returns>
/// <exception cref="NullReferenceException">If <paramref name="source"/> is null.</exception>
public static IEnumerable<T[]> Parititon<T>(this IEnumerable<T> source, int size)
{
return PartitionHelper(source, size);
}
/// <summary>
/// Splits a sequence of chars into fixed length strings.
/// </summary>
/// <param name="source">The source enumeration.</param>
/// <param name="size">The maximum size of each partition.</param>
/// <returns>A reference to the enumeration.</returns>
/// <exception cref="NullReferenceException">If <paramref name="source"/> is null.</exception>
public static IEnumerable<string> Parititon(this IEnumerable<char> source, int size)
{
return PartitionHelper(source, size).Select(x => new string(x));
}
/// <summary>
/// Picks random elements out of an enumeration.
/// </summary>
/// <typeparam name="T">The enumeration type.</typeparam>
/// <param name="source">The source enumeration.</param>
/// <param name="count">The maximum number of items to return.</param>
/// <returns>A reference to the enumeration.</returns>
/// <exception cref="NullReferenceException">If <paramref name="source"/> is null.</exception>
public static IEnumerable<T> Sample<T>(this IEnumerable<T> source, int count)
{
return source.Select(item => new { Key = Random.NextDouble(), Value = item })
.OrderBy(pair => pair.Key)
.Take(count)
.Select(pair => pair.Value);
}
private static IEnumerable<T[]> PartitionHelper<T>(IEnumerable<T> items, int size)
{
return items.Select((value, index) => new { value, index })
.GroupBy(x => x.index / size)
.Select(x => x.Select(v => v.value).ToArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment