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 wr开发者_运维技巧ite 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)
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 :)
the shortest way is
new T[]{value}
Edit Just thought of mentioning some of my favourite 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
Very convenient to define literal lists in any way, shape or form
Another simple way:
IEnumerable<int> = new [] {42};
Yet another simple way:
internal static IEnumerable<T> Enumerable<T>(this T obj)
{
yield return obj;
}
//
var enumerable = 42.Enumerable();
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.
精彩评论