How can I create a singleton IEnumerable?

孤街浪徒 提交于 2019-12-19 12:28:12

问题


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.


回答1:


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



回答2:


I use

Enumerable.Repeat(entity, 1);



回答3:


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



来源:https://stackoverflow.com/questions/4960091/how-can-i-create-a-singleton-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!