Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert IList or IEnumerable to Array

Tags:

c#

nhibernate

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.

like image 737
jishi Avatar asked Nov 06 '08 13:11

jishi


People also ask

Does array implement IEnumerable?

All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.

Can Linq be used on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What is ToArray C#?

ToArray() Method in C# This method(comes under System. Collections namespace) is used to copy a Stack to a new array. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop.


2 Answers

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; } 
like image 63
Jon Skeet Avatar answered Sep 23 '22 11:09

Jon Skeet


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(); 
like image 44
Michael Joyce Avatar answered Sep 22 '22 11:09

Michael Joyce