views:

1265

answers:

3

i have a generic ICollection. what is the best way to convert to string[]. using dotnet 2.0

+4  A: 

You could use the following snippet to convert it to an ordinary array:

string[] array = new string[collection.Size];
collection.CopyTo(array, 0);

That should do the job :)

AdrianoKF
do i need to initialize the array with the right size first .. cant i just do this: string[] futures = new string[] {}; FutureFVDictionary.Keys.CopyTo(futures, 0); ;
ooo
The array must first be initialized to the correct size - otherwise CopyTo will fail with an ArgumentException.
AdrianoKF
with List<String>(mycoll).ToArray() you don't have to worry about size.
gimel
+1  A: 

In the (trivial) case of ICollection<String>, use ToArray:

String[] GetArray(ICollection<String> mycoll)
{
    return mycoll.ToArray<String>();
}

EDIT: with .Net 2.0, you can return the array with an extra List<String>:

String[] GetArray(ICollection<String> mycoll)
{
    List<String> result = new List<String>(mycoll);
    return result.ToArray();
}
gimel
The compiler can infer the type argument, so mycoll.ToArray() would be fine, without needing the <string> part.
Daniel Earwicker
The List<T>.ToArray method uses an array copy, so doing the array copy directly would be the better option than creating a list, which is another object.
Cameron MacFarland
List<String>(mycoll).ToArray() abstracts the array creation and copying details.
gimel
+3  A: 

If you're using C# 3.0 and .Net framework 3.5, you should be able to do:

ICollection<string> col = new List<string>() { "a","b"};
string[] colArr = col.ToArray();

of course, you must have "using System.Linq;" at the top of the file

CVertex
Also List<T> has a ToArray method since .NET 2.0, so if you're using List<T> you don't need System.Linq
Cameron MacFarland
He asked for ICollection<string>
CVertex