Best way to convert IList or IEnumerable to Array

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!