可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
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.
Is there any better way? I went with the CopyTo-approach.
回答1:
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; }
回答2:
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();
回答3:
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(); }
回答4:
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