Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding single item to enumerable

Tags:

c#

linq

Is there a more elegant solution for adding an item to an IEnumerable than this

myNewIEnumerable = myIEnumerable.Concat ( Enumerable.Repeat (item, 1) );

?

Some context:

public void printStrings (IEnumerable<string> myStrings) {
   Console.WriteLine ("The beginning.");
   foreach (var s in myStrings) Console.WriteLine (s);
   Console.WriteLine ("The end.");
}

...

var result = someMethodDeliveringAnIEnumerableOfStrings ();
printStrings (result.Concat ( Enumerable.Repeat ("finished", 1) ) );
like image 748
JohnB Avatar asked Jul 13 '12 20:07

JohnB


1 Answers

Sure, there is. Concat() takes any IEnumerable<T>, including arrays:

var myNewIEnumerable = myIEnumerable.Concat(new[] { item });
like image 94
Frédéric Hamidi Avatar answered Sep 23 '22 05:09

Frédéric Hamidi