ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

ConcatTo

Adds a single element at the beginning of an enumerator

Source

static IEnumerable<T> ConcatTo<T>(IEnumerable<T> target, T element)
{
  return System.Linq.Concat(new[]{ element }, target);
}

or

static IEnumerable<T> ConcatTo<T>(IEnumerable<T> target, T element)
{
  yield return element;
  foreach(T e in target) yield return e;
}

Example

IEnumerable<String> x = new[]{"foo", "bar"};
x = x.ConcatTo("bla");
Console.WriteLine(string.Join('--',x));

// returns bla--foo--bar

Author: B.W. Kemps

Submitted on: 22 aug 2011

Language: C#

Type: System.Collections.IEnumerable<T>

Views: 2879