Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Best Way to Add One Item to an IEnumerable<T>?

Here's how I would add one item to an IEnumerable object:

//Some IEnumerable<T> object IEnumerable<string> arr = new string[] { "ABC", "DEF", "GHI" };  //Add one item arr = arr.Concat(new string[] { "JKL" }); 

This is awkward. I don't see a method called something like ConcatSingle() however.

Is there a cleaner way to add a single item to an IEnumerable object?

like image 546
user2023861 Avatar asked Mar 06 '13 15:03

user2023861


People also ask

How do I add an item to an IEnumerable?

What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");

What is IEnumerable T in C#?

IEnumerable interface is a generic interface which allows looping over generic or non-generic lists. IEnumerable interface also works with linq query expression. IEnumerable interface Returns an enumerator that iterates through the collection.

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

Is IEnumerable faster than List?

IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.


2 Answers

Nope, that's about as concise as you'll get using built-in language/framework features.

You could always create an extension method if you prefer:

arr = arr.Append("JKL"); // or arr = arr.Append("123", "456"); // or arr = arr.Append("MNO", "PQR", "STU", "VWY", "etc", "...");  // ...  public static class EnumerableExtensions {     public static IEnumerable<T> Append<T>(         this IEnumerable<T> source, params T[] tail)     {         return source.Concat(tail);     } } 
like image 133
LukeH Avatar answered Sep 23 '22 03:09

LukeH


IEnumerable is immutable collection, it means you cannot add, or remove item. Instead, you have to create a new collection for this, simply to convert to list to add:

var newCollection = arr.ToList(); newCollection.Add("JKL"); //is your new collection with the item added 
like image 26
cuongle Avatar answered Sep 20 '22 03:09

cuongle