What is an easy way to append or prepend a single value to an IEnumerable<T>?
I wrote custom extension methods to do this:
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item)
{
foreach (T i in source)
yield return i;
yield return item;
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
yield return item;
foreach (T i in source)
yield return i;
}
In your scenario, you would write:
var all = GetData().Prepend(GetHeaders());
As chilltemp commented, this does not mutate the original collection. In true Linq fashion, it generates a new IEnumerable<T>
.
Note: An eager null argument check is recommended for source
, but not shown for brevity.
Use the Enumerable.Concat extension method. For appending values instead of prepending, you'd just call Concat
in reverse. (ie: GetData().Concat(GetHeaders());
)
If GetHeaders()
returns a single string array, I'd personally probably wrap it in a single element array instead of a list:
var all = (new[] {GetHeaders()}).Concat(GetData());