There must be a good standard way of doing this, however every project I work on I have to write my own unity method, or create an inline array etc.
(I hope this will quickly get closed as a duplicate of a question with some great answers on this)
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");
IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
One simple way:
var singleElementSequence = Enumerable.Repeat(value, 1);
Or you could write your own extension method on an unconstrained generic type (usually a bad idea, admittedly... use with care):
public static IEnumerable<T> ToSingleElementSequence<T>(this T item)
{
yield return item;
}
Use as:
IEnumerable<String> sequence = "foo".ToSingleElementSequence();
I think I'd use Enumerable.Repeat
in preference though :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With