Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a singleton IEnumerable?

Does C# offer some nice method to cast a single entity of type T to IEnumerable<T>?

The only way I can think of is something like:

T entity = new T();
IEnumerable<T> = new List { entity }.AsEnumerable();

And I guess there should be a better way.

like image 442
Yippie-Ki-Yay Avatar asked Feb 10 '11 16:02

Yippie-Ki-Yay


2 Answers

Your call to AsEnumerable() is unnecessary. AsEnumerable is usually used in cases where the target object implements IQueryable<T> but you want to force it to use LINQ-to-Objects (when doing client-side filtering on a LINQ-compatible ORM, for example). Since List<T> implements IEnumerable<T> but not IQueryable<T>, there's no need for it.

Anyway, you could also create a single-element array with your item;

IEnumerable<T> enumerable = new[] { t };

Or Enumerable.Repeat

IEnumerable<T> enumerable = Enumerable.Repeat(t, 1);
like image 72
Adam Robinson Avatar answered Oct 22 '22 22:10

Adam Robinson


I use

Enumerable.Repeat(entity, 1);
like image 38
Mike Two Avatar answered Oct 22 '22 20:10

Mike Two