Best way to convert IList or IEnumerable to array

I have an HQL query that can generate either IList results or IEnumerable results.

However, I want it to return an Entity array that I select, what would be the best way to accomplish this? I can either list it, or build an array, or use CopyTo () a specific array.

Is there a better way? I went with the CopyTo approach.

+79
c # nhibernate
Nov 06 '08 at 13:25
source share
4 answers

What version of .NET are you using? If it's .NET 3.5, I just call ToArray() and do it with it.

If you have only universal IEnumerable, do something like this:

 IEnumerable query = ...; MyEntityType[] array = query.Cast<MyEntityType>().ToArray(); 

If you do not know the type inside this method, but the methods that call it know it, make this method general and try the following:

 public static void T[] PerformQuery<T>() { IEnumerable query = ...; T[] array = query.Cast<T>().ToArray(); return array; } 
+129
Nov 06 '08 at 13:34
source share

Add the following to your .cs file:

 using System.Linq; 

Then you can use the following extension method from System.Linq.Enumerable:

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

those.

 IEnumerable<object> query = ...; object[] bob = query.ToArray(); 
+31
Apr 18 '11 at 12:41
source share

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(); } 
+6
Jun 06 '13 at 19:43
source share

If you do not have Linq, I solved it as follows:

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

Hope this helps

+2
Jan 26 '16 at 16:38
source share



All Articles