开发者

C# Extension method for AddItem to IEnumerable<T>

开发者 https://www.devze.com 2023-01-05 16:43 出处:网络
What is the best way to add an item to 开发者_JS百科IEnumerable collection using Extension method?enumerable.Concat(new[]{ objToAdd })

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消