19

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
  • 3
    possible duplicate: http://stackoverflow.com/questions/4779442/return-single-instance-object-as-ienumerable – Justin Feb 10 '11 at 16:52
  • possible duplicate of [Passing a single item as IEnumerable](http://stackoverflow.com/questions/1577822/passing-a-single-item-as-ienumerablet) – nawfal Feb 17 '13 at 12:19

3 Answers3

25

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);
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • Notes: the array constructor syntax is significantly more efficient (but such micro-optimization is often not relevant); the repeat method on the other hand is guaranteed to be immutable. – Eamon Nerbonne Jan 31 '13 at 16:59
  • 1
    I like that Enumerable.Repeat allows you to hide the backing type. Also, I >assume< it's probably implemented with a loop/yield, and so can be the basis for a deferred execution implementation. – Sprague Jun 18 '13 at 11:55
  • @Sprague: If by "hide the backing type", you're referring to the ability to call `Repeat` without explicitly specifying the generic arguments, then the implicit array syntax (`new[] { t }`) does the same thing. – Adam Robinson Jun 18 '13 at 12:19
  • @AdamRobinson No, perhaps a confusing choice of words on my part. I was referring to the implementation of IEnumerable (array v. list v. value-yielding function) – Sprague Jun 18 '13 at 15:14
6

I use

Enumerable.Repeat(entity, 1);
Mike Two
  • 44,935
  • 9
  • 80
  • 96
6
var entity = new T();
var singleton = Enumerable.Repeat(entity, 1);

(Although I'd probably just do var singleton = new[] { entity }; in most situations, especially if it was only for private use.)

LukeH
  • 263,068
  • 57
  • 365
  • 409