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

后端 未结 11 622
感动是毒
感动是毒 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:53

    One way would be to create a singleton-sequence out of the item (such as an array), and then Concat it onto the original:

    image.Layers.Concat(new[] { image.ParentLayer } )
    

    If you're doing this really often, consider writing an Append (or similar) extension-method, such as the one listed here, which would let you do:

    image.Layers.Append(image.ParentLayer)
    

    .NET Core Update (per the "best" answer below):

    Append and Prepend have now been added to the .NET Standard framework, so you no longer need to write your own. Simply do this:

    image.Layers.Append(image.ParentLayer)
    
    0 讨论(0)
  • 2021-02-04 23:54

    I once made a nice little function for this:

    public static class CoreUtil
    {    
        public static IEnumerable<T> AsEnumerable<T>(params T[] items)
        {
            return items;
        }
    }
    

    Now this is possible:

    image.Layers.Append(CoreUtil.AsEnumerable(image.ParentLayer, image.AnotherLayer))
    
    0 讨论(0)
  • 2021-02-05 00:00
    /// <summary>Concatenates elements to a sequence.</summary>
    /// <typeparam name="T">The type of the elements of the input sequences.</typeparam>
    /// <param name="target">The sequence to concatenate.</param>
    /// <param name="items">The items to concatenate to the sequence.</param>
    public static IEnumerable<T> ConcatItems<T>(this IEnumerable<T> 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)
    
    0 讨论(0)
  • 2021-02-05 00:01

    If you like the syntax of .With, write it as an extension method. IEnumerable won't notice another one.

    0 讨论(0)
  • 2021-02-05 00:01

    I use the following extension methods to avoid creating a useless Array:

    public static IEnumerable<T> ConcatSingle<T>(this IEnumerable<T> enumerable, T value) {
       return enumerable.Concat(value.Yield());
    }
    
    public static IEnumerable<T> Yield<T>(this T item) {
        yield return item;
    }
    
    0 讨论(0)
提交回复
热议问题