Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a single value of type T into an IEnumerable<T>? [duplicate]

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)

like image 421
Ian Ringrose Avatar asked Jun 21 '11 09:06

Ian Ringrose


People also ask

How do I add items to an IEnumerable?

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

What is IEnumerable T?

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

Can we convert IEnumerable to List C#?

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


1 Answers

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

like image 58
Jon Skeet Avatar answered Sep 18 '22 08:09

Jon Skeet