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:
ItemArr开发者_StackOverflow社区ay = 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?
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.
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);
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.
精彩评论