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
2008-11-30 11:40:42
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
2008-11-30 11:54:38
The array must first be initialized to the correct size - otherwise CopyTo will fail with an ArgumentException.
AdrianoKF
2008-11-30 12:06:27
with List<String>(mycoll).ToArray() you don't have to worry about size.
gimel
2008-11-30 12:40:24
+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
2008-11-30 11:43:58
The compiler can infer the type argument, so mycoll.ToArray() would be fine, without needing the <string> part.
Daniel Earwicker
2008-11-30 11:46:43
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
2008-11-30 12:27:49
List<String>(mycoll).ToArray() abstracts the array creation and copying details.
gimel
2008-11-30 12:38:56
+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
2008-11-30 11:44:52
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
2008-11-30 12:13:19