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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With