Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICollection<string> to string[]

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?

like image 269
leora Avatar asked Nov 30 '08 11:11

leora


People also ask

What is ICollection in C# with example?

The ICollection interface in C# defines the size, enumerators, and synchronization methods for all nongeneric collections. It is the base interface for classes in the System. Collections namespace. The following are the properties of ICollection interface − Sr.No.


2 Answers

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

like image 144
AdrianoKF Avatar answered Sep 28 '22 13:09

AdrianoKF


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

like image 21
CVertex Avatar answered Sep 28 '22 15:09

CVertex