Append & Prepend
(These have been added to .NET since this answer was written.)
/// Adds a single element to the end of an IEnumerable.
/// Type of enumerable to return.
/// IEnumerable containing all the input elements, followed by the
/// specified additional element.
public static IEnumerable Append(this IEnumerable source, T element)
{
if (source == null)
throw new ArgumentNullException("source");
return concatIterator(element, source, false);
}
/// Adds a single element to the start of an IEnumerable.
/// Type of enumerable to return.
/// IEnumerable containing the specified additional element, followed by
/// all the input elements.
public static IEnumerable Prepend(this IEnumerable tail, T head)
{
if (tail == null)
throw new ArgumentNullException("tail");
return concatIterator(head, tail, true);
}
private static IEnumerable concatIterator(T extraElement,
IEnumerable source, bool insertAtStart)
{
if (insertAtStart)
yield return extraElement;
foreach (var e in source)
yield return e;
if (!insertAtStart)
yield return extraElement;
}