I have a object of type ICollection<string>
. What is the best way to convert to string[]
.
How can this be done in .NET 2?
How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?
I have a object of type ICollection<string>
. What is the best way to convert to string[]
.
How can this be done in .NET 2?
How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?
You could use the following snippet to convert it to an ordinary array:
string[] array = new string[collection.Count];
collection.CopyTo(array, 0);
That should do the job :)
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
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();
}