C# 将 IList 或 IEnumerable 转换为 Array 的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/268671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to convert IList or IEnumerable to Array
提问by jishi
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
我有一个 HQL 查询,它可以生成结果的 IList 或结果的 IEnumerable。
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.
有没有更好的办法?我采用了 CopyTo 方法。
采纳答案by Jon Skeet
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
您使用的是哪个版本的 .NET?如果它是 .NET 3.5,我只会调用ToArray()
并完成它。
If you only have a non-generic IEnumerable, do something like this:
如果您只有一个非通用的 IEnumerable,请执行以下操作:
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;
}
回答by Michael Joyce
Put the following in your .cs file:
将以下内容放入您的 .cs 文件中:
using System.Linq;
You will then be able to use the following extension method from System.Linq.Enumerable:
然后,您将能够使用 System.Linq.Enumerable 中的以下扩展方法:
public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)
I.e.
IE
IEnumerable<object> query = ...;
object[] bob = query.ToArray();
回答by Philippe Matray
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();
}
回答by Lug
In case you don't have Linq, I solved it the following way:
如果您没有 Linq,我可以通过以下方式解决它:
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
希望能帮助到你