Reputation: 31887
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.
Upvotes: 7
Views: 12869
Reputation: 1002
If you are forced to have IList, then to get an array...
IList list;
var array = new List<string>(list).ToArray()
Upvotes: 4
Reputation: 22323
try:
public static T[] ToArray<T>(this IList<T> list)
{
if (list is Array) return (T[]) list;
T[] retval = new T[list.Count];
for (int i = 0; i < retval.Length; i++)
retval[i] = list[i];
return retval;
}
Its only a rough .May be its help.
Upvotes: 1
Reputation: 10346
ToArray is an extension method of IEnumerable, and IList implement IEnumerable. You can do it if you import that.
Upvotes: 3
Reputation: 241711
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?
Upvotes: 27
Reputation: 115528
One way or another, you are going to have to create an array and fill the contents of it with what is in the list. This is the most straight forward way of doing it.
var arr = new string[Your_List.Count]
for(var ii = 0; ii < arr.Length; ii++){
arr[ii] = Your_List[ii];
}
Upvotes: 1