5

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) ) );
JohnB
  • 12,707
  • 4
  • 36
  • 64

3 Answers3

5

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

var myNewIEnumerable = myIEnumerable.Concat(new[] { item });
Frédéric Hamidi
  • 249,845
  • 40
  • 466
  • 467
2

Maybe the easiest way to append a single element to an IEnumerable<T> is to use this AsIEnumerable extension (although Eric Lippert advises against creating extension for objects):

public static IEnumerable<T> AsIEnumerable<T>(this T obj)
{
    yield return obj;
}  

var appended = source.Concat(element.AsIEnumerable())

or use this Append<T> extension: https://stackoverflow.com/a/3645715/284240

Community
  • 1
  • 1
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
  • The AsEnumerable () is what I was looking for. Thank you very much! – JohnB Jul 13 '12 at 20:46
  • Just a remark: As I just noticed, it's important not to confuse AsIEnumerable with AsEnumerable ! It must be AsIEnumerable, of course. – JohnB Jul 21 '12 at 09:14
  • @JohnB: Well, that is the core of this answer (and your question) since a single object is never an `IEnumerable` of it's type and has no `AsEnumerable()` method. We could rename it to `AsEnumerable` but that could cause misunderstandings even more. – Tim Schmelter Jul 21 '12 at 14:32
1

You can define your own SingleConcat extension methods like so

public static class CustomConcat
    {
        public static IEnumerable<T> SingleConcat<T>(this IEnumerable<T> first, T lastElement)
        {
            foreach (T t in first)
            {
                yield return t;
            }

            yield return lastElement;
        }
    }

    class Program
    {


        static void Main(string[] args)
        {
            List<int> mylist = new List<int> { 1 , 2 , 3};

            var newList = mylist.SingleConcat(4);

            foreach (var s in newList)
            {
                Console.WriteLine(s);
            }

            Console.Read();
        }
    }

This should print 1,2,3 followed by a 4

parapura rajkumar
  • 23,647
  • 1
  • 53
  • 83