Skip to content

Instantly share code, notes, and snippets.

@johndkane
Last active September 23, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johndkane/8ff1825603781d71ce9b994f7a452961 to your computer and use it in GitHub Desktop.
Save johndkane/8ff1825603781d71ce9b994f7a452961 to your computer and use it in GitHub Desktop.
Two helpful methods (one extension) to enable scalar values to be used in an enumerable context, without needing to create an intermediary collection
namespace Your_Project
{
using System.Collections.Generic;
static public class Utility
{
/// <summary>
/// Extension method yields the given value verbatim allowing it to be used in an enumerable context.
/// USAGE: 1.YieldValue()
/// EXAMPLE: listOfNumbers.Union(1.YieldValue()); // using System.Linq
/// </summary>
static public IEnumerable<TValue> YieldValue<TValue>(this TValue item)
{
yield return item;
}
/// <summary>
/// Yields all the given method params to enable them in an enumerable context.
/// USAGE: foreach(var num in Utility.Values(1, 2, 3, 4, 5, 6));
/// </summary>
static public IEnumerable<T> Values<T>(params T[] values)
{
if (!(values is null))
foreach (var v in values)
yield return v;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment