Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a statement to prepend an element T to a IEnumerable<T>

Tags:

For example:

string element = 'a'; IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };  IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd'  
like image 483
jyoung Avatar asked Apr 29 '09 14:04

jyoung


2 Answers

I take it you can't just Insert into the existing list?

Well, you could use new[] {element}.Concat(list).

Otherwise, you could write your own extension method:

    public static IEnumerable<T> Prepend<T>(             this IEnumerable<T> values, T value) {         yield return value;         foreach (T item in values) {             yield return item;         }     }     ...      var singleList = list.Prepend("a"); 
like image 80
Marc Gravell Avatar answered Sep 27 '22 16:09

Marc Gravell


Since .NET framework 4.7.1 there is LINQ method for that:

list.Prepend("a"); 

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend?view=netframework-4.7.1

like image 33
videokojot Avatar answered Sep 27 '22 16:09

videokojot