Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert IList<string> to a string[] without using Linq

Tags:

c#

.net

.net-2.0

I'm not sure what is the best way to convert an IList<string> (IList does not implement the ToArray property) to an string[] array.

I cannot use Linq because I'm compiling with .NET 2.0. Any ideas will be wellcome.

like image 949
Daniel Peñalba Avatar asked Nov 10 '11 14:11

Daniel Peñalba


2 Answers

Use ICollection<T>.CopyTo:

string[] strings = new string[list.Count];
list.CopyTo(strings, 0);

I'm not quite sure if I understand the no-LINQ restriction though? It sounds like you would use ToArray if IList<T> had it. But it turns out it does because IEnumerable<T>.ToArray is an extension method defined on IEnumerable<T> of which IList<T> implements. So why don't you just use that?

like image 121
jason Avatar answered Sep 19 '22 15:09

jason


If you are forced to have IList, then to get an array...

IList list; 
var array = new List<string>(list).ToArray()
like image 34
jsirr13 Avatar answered Sep 21 '22 15:09

jsirr13