Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an easy way to append or prepend a single value to an IEnumerable<T>?

I need to prepend a single value to an IEnumerable (in this case, IEnumerable<string[]>). In order to do that, I'm creating a List<T> just to wrap the first value so that I can call Concat:

// get headers and data together
IEnumerable<string[]> headers = new List<string[]> {
    GetHeaders()
};
var all = headers.Concat(GetData());

Yuck. Is there a better way? And how would you handle the opposite case of appending a value?

like image 530
Gabe Moothart Avatar asked Aug 04 '10 18:08

Gabe Moothart


1 Answers

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.

like image 163
Greg Avatar answered Oct 20 '22 01:10

Greg