What is the best way to add an item to IEnumerable collection using Extension method?
actually this is creating new enumerable, not adding to existing one
Andrey
2010-07-06 10:24:00
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
2010-07-06 10:32:58
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
2010-07-06 10:38:05
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
2010-07-06 10:54:44
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
2010-07-06 11:07:26
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
2010-07-06 10:18:28
+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
2010-07-06 10:19:26