Adding a single item to an enumerated

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

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

?

In 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) ) );
+5
source share
3 answers

Perhaps the easiest way to add one element to IEnumerable<T>is to use this extension AsIEnumerable(although Eric Lippert advises against creating an extension for objects)

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

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

or use the extension Append<T>: fooobar.com/questions/24916 / ...

+2
source

Of course have. Concat () accepts any IEnumerable<T>, including arrays:

var myNewIEnumerable = myIEnumerable.Concat(new[] { item });
+5
source

SingleConcat

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();
        }
    }

1,2,3, 4

+1

All Articles