如何创建一个单独的IEnumerable? [英] How can I create a singleton IEnumerable?
问题描述
请问C#提供了一些不错的方法,铸铅字 T
的一个实体的IEnumerable< T>
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.
推荐答案
您调用 AsEnumerable()
是不必要的。 AsEnumerable
通常情况下使用,其中目标对象实现的IQueryable< T>
,但要迫使它使用LINQ -to-对象(上一个LINQ兼容的ORM做客户端筛选时,例如)。由于列表< T>
工具的IEnumerable< T>
而不是的IQueryable< T>
,有没有必要为它
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 };
或 Enumerable.Repeat
IEnumerable<T> enumerable = Enumerable.Repeat(t, 1);
这篇关于如何创建一个单独的IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!