codymanix
codymanix

Reputation: 29490

Insert element with LINQ

Given I have a IEnumerable (e) and a single value of T (t). What is the simplest way of doing:

IEnumerable<T> newCollection = t+e

At the moment I am doing:

ItemArray = Enumerable.Repeat<object>(t, 1).Concat(e);

which is rather unreadable, since I'am doing not real repeat here. I also tried:

IEnumerable<T> newCollection = new List<object> { t}.Concat(e);

But this one creates an unecessary List object which also isn't optimal.

Does anyone have a better idea?

Upvotes: 1

Views: 214

Answers (3)

KeithS
KeithS

Reputation: 71573

Instead of a List, which is a more complex object, try creating just a simple array. It may be faster:

IEnumerable<T> newCollection = new [] { t}.Concat(e);

I'll tell you now that, to use Linq to add this item, you must create a new collection of some type. This is because Linq is designed to work with enumerables, and because it is side-effect-free; no matter what you do in a Linq statement, the source enumerables are left as they were before you started (unless you're dealing with a custom collection that has side effects inherent in enumerating it). The upshot is that, at some level, Linq must treat your single item as a collection containing that one item, so that it can enumerate through that collection to produce whatever output you desire. This is true whether you hide the implementation behind an extension method like those in MoreLINQ or not.

Upvotes: 2

Bryan Watts
Bryan Watts

Reputation: 45445

Jon Skeet's answer is the most semantically valuable. However, if you still want a way to do it inline, you can use an implicitly-typed array:

newCollection = new[] { t }.Concat(e);

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500615

In MoreLINQ we have a Prepend method you may be interested in taking. So your code would be:

ItemArray = e.Prepend(t);

EDIT: Under the hood, Prepend only does what your current code does - I'm really just suggesting refactoring it to a method which hides the Repeat / Concat part, and leaves you with more readable calling code.

Upvotes: 6

Related Questions