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?
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");
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.
Unfortunately, List<T>. AddRange isn't defined in any interface.
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.
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); } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With