tags:

views:

87

answers:

3

What is the best way to add an item to IEnumerable collection using Extension method?

+8  A: 
enumerable.Concat(new[]{ objToAdd })
Mehrdad Afshari
actually this is creating new enumerable, not adding to existing one
Andrey
Yeah, but since `IEnumerable<T>` **interface** itself is read-only, that's the only possible way. Adding to underlying collection is not always an option (e.g. when the underlying collection doesn't really exist).
Mehrdad Afshari
To emphasise what `Andrey` commented: It does not **exactly** implement an `AddItem` method (eg. add `item` to the `IEnumerable`) as you would expect it to work. More fitting name for such a method would be `Concat(item)` - there you would expect the method to return a new IEnumerable.
Jaroslav Jandek
Well, I will use this method in combination with NHibernate. The collection is a property of an EntityObject and this object controls CRUD operations for the collection. I must try it but I am not sure in what will result this when we create brand new enumerable after adding the new item.
mynkow
You will have to do `eo.IEnumProperty = eo.IEnumProperty.AddItem(objToAdd );` which is not good since usually you define an `IEnumerable` property as `get`-only.
Jaroslav Jandek
A: 

I have this in my IEnumerableExtensions class, not sure its too efficient, but I use it very sparingly.

public static IEnumerable<T> Add<T>(this IEnumerable<T> enumerable, T item)
{
   var list = enumerable.ToList();
   list.Add(item);
   return list;
}
Jamiec
not good, this allocates additional memory. Mehrdad Afshari's answer is really better.
Andrey
Agree totally, which is why this is mostly unused and deprecated in my exytensions library.
Jamiec
+1  A: 

You cannot (directly). The purpose of the interface is to expose an enumerator.

Edit: You would have to convert the IEnumerable to another type (like a List) or concatenation to add, which would result not in adding to an existing IEnumerable, but concatenating to a new IEnumerable instead.

The only option would be to test if the if it implements any of the interfaces usable for adding like IList, ICollection, IDictionary, ILookup, ... and even then you won't be sure that you can add to an existing IEnumerable.

Jaroslav Jandek
And its implemented by enumerable (pun intended) classes which you *can* add to.
Jamiec
It's not *necessary* that an `IEnumerable` implementation can be added to. If it were, there would exist `IEnumerable.Add`. The comment is absolutely correct.
Dan Puzey