简体   繁体   English

IEnumerable的AddItem的C#扩展方法<T>

[英]C# Extension method for AddItem to IEnumerable<T>

使用扩展方法将项目添加到IEnumerable集合的最佳方法是什么?

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. 编辑 :您将不得不将IEnumerable转换为另一种类型(例如List )或要添加的并置,这不会导致添加到现有IEnumerable ,而是导致IEnumerable新的IEnumerable

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 . 唯一的选择是测试它是否实现了可用于添加的任何接口,例如IList,ICollection,IDictionary,ILookup等,即使如此,您也不确定将其添加到现有的IEnumerable

I have this in my IEnumerableExtensions class, not sure its too efficient, but I use it very sparingly. 我在IEnumerableExtensions类中有此功能,但不确定它的效率如何,但我非常谨慎地使用它。

public static IEnumerable<T> Add<T>(this IEnumerable<T> enumerable, T item)
{
   var list = enumerable.ToList();
   list.Add(item);
   return list;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM