Last active
September 23, 2019 22:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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