How to convert a single value of type T to IEnumerable <T>?

There should be a good standard way to do this, however, each project I am working on should write its own unity method or create an inline array, etc.

(I hope this closes quickly as a duplicate of the question with some wonderful answers to this)

+7
source share
4 answers

One easy way:

var singleElementSequence = Enumerable.Repeat(value, 1); 

Or you can write your own extension method on an unlimited generic type (this is usually a bad idea, admittedly ... use with caution):

 public static IEnumerable<T> ToSingleElementSequence<T>(this T item) { yield return item; } 

Use as:

 IEnumerable<String> sequence = "foo".ToSingleElementSequence(); 

I would prefer to use Enumerable.Repeat :)

+13
source

Edit Just thought of mentioning some of my favorite devices in LINQ:

  internal static IEnumerable<T> Concat<T>(params T[] objs) { return objs; } internal static IEnumerable<T> Concat<T>(this IEnumerable<T> e, params T[] objs) { return e.Concat(objs); } internal static IEnumerable<T> Concat<T>(this IEnumerable<T> e, params IEnumerable<T>[] seqs) { foreach (T t in e) yield return t; foreach (var seq in seqs) foreach (T t in seq) yield return t; } // this allows you to var e1 = Concat(1,2,3); // 1,2,3 var e2 = e1.Concat(4,5,6); // 1,2,3,4,5,6, var e3 = e2.Concat(e2, e1, Concat(42)); // 1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,42 

It is very convenient to define literal lists in any way, form or form

Another easy way:

  IEnumerable<int> = new [] {42}; 

Another easy way:

  internal static IEnumerable<T> Enumerable<T>(this T obj) { yield return obj; } // var enumerable = 42.Enumerable(); 
+4
source

the shortest way

 new T[]{value} 
+3
source

You can define your own extension method:

 public static class IEnumerableExt { // usage: someObject.AsEnumerable(); public static IEnumerable<T> AsEnumerable<T>(this T item) { yield return item; } } 

There is nothing in the .NET Framework that performs this task.

+1
source

All Articles