[英]How can I create a singleton IEnumerable?
Does C# offer some nice method to cast a single entity of type T
to IEnumerable<T>
? C# 是否提供了一些不错的方法将
T
类型的单个实体转换为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.而且我想应该有更好的方法。
Your call to AsEnumerable()
is unnecessary. 您对
AsEnumerable()
调用是不必要的。 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). AsEnumerable
通常用于目标对象实现IQueryable<T>
但是你想强制它使用LINQ-to-Objects(例如,在LINQ兼容的ORM上进行客户端过滤时)。 Since List<T>
implements IEnumerable<T>
but not IQueryable<T>
, there's no need for it. 由于
List<T>
实现IEnumerable<T>
但不实现IQueryable<T>
,因此不需要它。
Anyway, you could also create a single-element array with your item; 无论如何,您还可以使用您的项目创建单元素数组;
IEnumerable<T> enumerable = new[] { t };
Or Enumerable.Repeat
或者
Enumerable.Repeat
IEnumerable<T> enumerable = Enumerable.Repeat(t, 1);
我用
Enumerable.Repeat(entity, 1);
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.) (虽然我可能只是做
var singleton = new[] { entity };
在大多数情况下,特别是如果它仅供私人使用。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.