19

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?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
leora
  • 188,729
  • 360
  • 878
  • 1,366

3 Answers3

35

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 :)

bryanbcook
  • 16,210
  • 2
  • 40
  • 69
AdrianoKF
  • 2,891
  • 1
  • 25
  • 31
  • 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); ; – leora Nov 30 '08 at 11:54
  • 1
    The array must first be initialized to the correct size - otherwise CopyTo will fail with an ArgumentException. – AdrianoKF Nov 30 '08 at 12:06
  • with List(mycoll).ToArray() you don't have to worry about size. – gimel Nov 30 '08 at 12:40
  • @AdrianoKF The first line should be `string[] array = new string[collection.Count];`, since `ICollection` has a [`Count`](http://msdn.microsoft.com/en-us/library/5s3kzhec.aspx) property. – Paolo Moretti Mar 30 '12 at 09:59
8

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
  • 17,997
  • 28
  • 94
  • 124
7

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
  • 83,368
  • 10
  • 76
  • 104