tags:

views:

8974

answers:

2

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.

A: 

CopyTo is it.

plinth
Lemme explain you why is is NOT CopyTo: 1) CopyTo is not a member/extension of IEnumerable, 2) to use CopyTo, you first have to get the underlying IEnumerable array, which you then don't need the CopyTo
Shimmy
+13  A: 

Which version of .NET are you using? If it's .NET 3.5 I'd just call ToArray() and have done with it.

If you've only got a nongeneric IEnumerable, do something like this:

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

If you don't know the type within that method, but callers will know it, much the method generic:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}
Jon Skeet
It's 3.5 but the IQuery doesn't have a ToArray, nor does IEnumerable or IList either as far as I can tell?
jishi
Thanks man, that was useful. Would you say that there is any difference in calling Cast<>() from the IList vs the IEnumerable?
jishi
No - there's just the one extension method. (It's not within the interface itself.)
Jon Skeet
What if I don't know what MyEntityType will be when I create that array?
towps
Then how are you going to use it afterwards anyway? If only your *caller* knows, then make it a generic type parameter in the method containing this code.
Jon Skeet
not sure i completely follow you. you mean something like var array = list.Cast<listType>().ToArray(); ?
towps
@towps: Will edit my post.
Jon Skeet
I want to convert a non-generic IEnumerable to an Array, how should I do it? I prefer not using the cast, as there is no point in it.
Shimmy
@Shimmy: Yes there is... aside from anything else, it's telling the compiler what kind of array to expect! If you only want an `object[]` just use `Cast<object>`. The nongeneric `IEnumerable` doesn't have a `ToArray` extension method, so you can't just call `foo.ToArray<object>` or anything like that.
Jon Skeet
I am basically looking for the non-generic ToArray() method, it's already on my extension library using Cast, thanks Jon!
Shimmy