C# Extension method for AddItem to IEnumerable<T>
What is the best way to add an item to 开发者_JS百科IEnumerable collection using Extension method?
enumerable.Concat(new[]{ objToAdd })
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
.
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;
}
精彩评论