Is there a Linq method to add a single item to an IEnumerable?

后端 未结 11 760
感动是毒
感动是毒 2021-02-04 23:10

Basically I am trying to do something like this:

image.Layers

which returns an IEnumerable for all layers except the Parent layer,

11条回答
  •  半阙折子戏
    2021-02-04 23:52

    Many implementations have been given already. Mine looks a bit different (but performs just as well)

    Also, I find it practicle to also have control over the ORDER. thus often, I also have a ConcatTo method, putting the new element op front.

    public static class Utility
    {
        /// 
        /// Adds the specified element at the end of the IEnummerable.
        /// 
        /// The type of elements the IEnumerable contans.
        /// The target.
        /// The item to be concatenated.
        /// An IEnumerable, enumerating first the items in the existing enumerable
        public static IEnumerable ConcatItem(this IEnumerable target, T item)
        {
            if (null == target) throw new ArgumentException(nameof(target));
            foreach (T t in target) yield return t;
            yield return item;
        }
    
        /// 
        /// Inserts the specified element at the start of the IEnumerable.
        /// 
        /// The type of elements the IEnumerable contans.
        /// The IEnummerable.
        /// The item to be concatenated.
        /// An IEnumerable, enumerating first the target elements, and then the new element.
        public static IEnumerable ConcatTo(this IEnumerable target, T item)
        {
            if (null == target) throw new ArgumentException(nameof(target));
            yield return item;
            foreach (T t in target) yield return t;
        }
    }
    

    Or alternatively, use an implicitly created array. (using the params keyword) so you can call the method to add one or more items at a time:

    public static class Utility
    {
        /// 
        /// Adds the specified element at the end of the IEnummerable.
        /// 
        /// The type of elements the IEnumerable contans.
        /// The target.
        /// The items to be concatenated.
        /// An IEnumerable, enumerating first the items in the existing enumerable
        public static IEnumerable ConcatItems(this IEnumerable target, params T[] items) =>
            (target ?? throw new ArgumentException(nameof(target))).Concat(items);
    
        /// 
        /// Inserts the specified element at the start of the IEnumerable.
        /// 
        /// The type of elements the IEnumerable contans.
        /// The IEnummerable.
        /// The items to be concatenated.
        /// An IEnumerable, enumerating first the target elements, and then the new elements.
        public static IEnumerable ConcatTo(this IEnumerable target, params T[] items) =>
            items.Concat(target ?? throw new ArgumentException(nameof(target)));
    

提交回复
热议问题