有没有一个 Linq 方法可以将一个项目添加到 IEnumable < T > ?

我正在尝试做这样的事情:

image.Layers

返回除了 Parent层以外的所有层的 IEnumerable<Layer>,但是在某些情况下,我只想做:

image.Layers.With(image.ParentLayer);

因为它只在少数地方使用,而 image.Layers满足通常使用的100次。这就是为什么我不想让另一个属性也返回 Parent层。

32292 次浏览

You can use Enumerable.Concat:

var allLayers = image.Layers.Concat(new[] {image.ParentLayer});

There is the Concat method which joins two sequences.

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)

You can do something like:

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

which concats the enum with a single-element array containing the thing you want to add

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

There is no single method which does this. The closest is the Enumerable.Concat method but that tries to combine an IEnumerable<T> with another IEnumerable<T>. You can use the following to make it work with a single element

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

Or just add a new extension method

public static IEnumerable<T> ConcatSingle<T>(this IEnumerable<T> enumerable, T value) {
return enumerable.Concat(new [] { value });
}

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))

EDIT

Like @cpb mentioned correctly: Append and Prepend comes out of the box now. (source) Microsoft also decided to implement both a way to add items at the start end on the end. They created a AppendPrepend1Iterator class, that has some optimizations (e.g. getting the count if the original underlying collection is an ICollection)

I'll leave my answer for historical reasons.


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
{
/// <summary>
/// Adds the specified element at the end of the IEnummerable.
/// </summary>
/// <typeparam name="T">The type of elements the IEnumerable contans.</typeparam>
/// <param name="target">The target.</param>
/// <param name="item">The item to be concatenated.</param>
/// <returns>An IEnumerable, enumerating first the items in the existing enumerable</returns>
public static IEnumerable<T> ConcatItem<T>(this IEnumerable<T> target, T item)
{
if (null == target) throw new ArgumentException(nameof(target));
foreach (T t in target) yield return t;
yield return item;
}


/// <summary>
/// Inserts the specified element at the start of the IEnumerable.
/// </summary>
/// <typeparam name="T">The type of elements the IEnumerable contans.</typeparam>
/// <param name="target">The IEnummerable.</param>
/// <param name="item">The item to be concatenated.</param>
/// <returns>An IEnumerable, enumerating first the target elements, and then the new element.</returns>
public static IEnumerable<T> ConcatTo<T>(this IEnumerable<T> 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
{
/// <summary>
/// Adds the specified element at the end of the IEnummerable.
/// </summary>
/// <typeparam name="T">The type of elements the IEnumerable contans.</typeparam>
/// <param name="target">The target.</param>
/// <param name="items">The items to be concatenated.</param>
/// <returns>An IEnumerable, enumerating first the items in the existing enumerable</returns>
public static IEnumerable<T> ConcatItems<T>(this IEnumerable<T> target, params T[] items) =>
(target ?? throw new ArgumentException(nameof(target))).Concat(items);


/// <summary>
/// Inserts the specified element at the start of the IEnumerable.
/// </summary>
/// <typeparam name="T">The type of elements the IEnumerable contans.</typeparam>
/// <param name="target">The IEnummerable.</param>
/// <param name="items">The items to be concatenated.</param>
/// <returns>An IEnumerable, enumerating first the target elements, and then the new elements.</returns>
public static IEnumerable<T> ConcatTo<T>(this IEnumerable<T> target, params T[] items) =>
items.Concat(target ?? throw new ArgumentException(nameof(target)));

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

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)

See What are the 43 APIs that are in .Net Standard 2.0 but not in .Net Framework 4.6.1? for a great list of new functionality.