到IList转换的最佳方式或IEnumerable的到阵列 [英] Best way to convert IList or IEnumerable to Array
问题描述
我有一个HQL查询,可以产生两种结果,一个IList,或结果的IEnumerable。
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
不过,我希望它返回我选择实体的数组,这将是实现这个目的的最好方法是什么?我可以通过它枚举和构建阵列,或使用CopyTo从()定义的数组。
However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.
有没有什么更好的办法?我去的CopyTo从的方法。
Is there any better way? I went with the CopyTo-approach.
推荐答案
.NET哪个版本您使用的?如果它是.NET 3.5的,我只是叫 ToArray的()
,并用它做。
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
如果你只有一个非通用IEnumerable的,做这样的事情:
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
如果你不知道该方法中的类型,但该方法的调用者知道它,使该方法一般和尝试这个办法:
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
这篇关于到IList转换的最佳方式或IEnumerable的到阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!