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

后端 未结 11 638
感动是毒
感动是毒 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-05 00:00

    /// Concatenates elements to a sequence.
    /// The type of the elements of the input sequences.
    /// The sequence to concatenate.
    /// The items to concatenate to the sequence.
    public static IEnumerable ConcatItems(this IEnumerable target, params T[] items)
    {
        if (items == null)
            items = new [] { default(T) };
        return target.Concat(items);
    }
    

    This solution is based on realbart's answer. I adjusted it to allow the use of a single null value as a parameter:

    var newCollection = collection.ConcatItems(null)
    

提交回复
热议问题