将 IList 或 IEnumable 转换为 Array 的最佳方法

我有一个 HQL 查询,它既可以生成结果的 ILlist,也可以生成结果的 IEnumable。

然而,我希望它返回一个我选择的 Entity 的数组,实现这一点的最佳方法是什么?我可以枚举它并构建数组,也可以使用 CopyTo ()定义数组。

还有更好的办法吗? 我选择了复制方式。

147187 次浏览

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

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

Put the following in your .cs file:

using System.Linq;

You will then be able to use the following extension method from System.Linq.Enumerable:

public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)

I.e.

IEnumerable<object> query = ...;
object[] bob = query.ToArray();

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");


return enumerable as T[] ?? enumerable.ToArray();
}

In case you don't have Linq, I solved it the following way:

    private T[] GetArray<T>(IList<T> iList) where T: new()
{
var result = new T[iList.Count];


iList.CopyTo(result, 0);


return result;
}

Hope it helps