Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to do something like this:

image.Layers 

which returns an IEnumerable<Layer> for all layers except the Parent layer, but in some cases, I just want to do:

image.Layers.With(image.ParentLayer); 

because it's only used in a few places compared to the 100s of the usual usage which is satisfied by image.Layers. That's why I don't want to make another property that also returns the Parent layer.

like image 934
Joan Venge Avatar asked Feb 03 '11 19:02

Joan Venge


People also ask

How can I add an item to a IEnumerable T collection?

What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");

Can you use LINQ on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

What is single () in C#?

C# Single() Method CsharpProgrammingServer Side Programming. Get only a single element of a sequence using the Single() method. Let's say we have a string array with only one element. string[] str = { "one" }; Now, get the element.


1 Answers

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) 
like image 195
Ani Avatar answered Sep 19 '22 15:09

Ani