C# Extension method for AddItem to IEnumerable<T>

心已入冬 提交于 2019-12-23 01:48:37

问题


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


回答1:


enumerable.Concat(new[]{ objToAdd })



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/3185320/c-sharp-extension-method-for-additem-to-ienumerablet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!