Here\'s how I would add one item to an IEnumerable object:
//Some IEnumerable object
IEnumerable arr = new string[] { \"ABC\", \"DEF\"
Append()
- is exactly what you need, it has been added to the .NET Standard (in 2017), so you no longer need to write your own extension methods. You can simply do this:
arr = arr.Append("JKL");
Since .NET is open source, here you can look on the implementation (it is more sophisticated than custom methods suggested above): https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/AppendPrepend.cs
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);
}
}
Write an extension method ConcatSingle
:)
public static IEnumerable<T> ConcatSingle<T>(this IEnumerable<T> source, T item)
{
return source.Concat(new [] { item } );
}
But you need to be more careful with your terminology.
You can't add an item to an IEnumerable<T>
. Concat
creates a new instance.
Example:
var items = Enumerable.Range<int>(1, 10)
Console.WriteLine(items.Count()); // 10
var original= items;
items = items.ConcatSingle(11);
Console.WriteLine(original.Count()); // 10
Console.WriteLine(items.Count()); // 11
As you can see, the original enumeration - which we saved in original
didn't change.
Since IEnumerable is read-only, you need to convert to list.
var new_one = arr.ToList().Add("JKL");
Or you can get a extension method like;
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, params T[] item)
{
return source.Concat(item);
}
You're assigning an array to an IEnumerable. Why don't you use the Array type instead of IEnumerable?
Otherwise you can use IList (or List) if you want to change the collection.
I use IEnumerable only for methods params when I need to read and IList (or List) when I need to change items in it.
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