将 IList 或 IEnumerable 转换为 Array 的最佳方法 [英] Best way to convert IList or IEnumerable to Array

查看:23
本文介绍了将 IList 或 IEnumerable 转换为 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 转换为 Array 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆