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

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

I cannot use Linq because I am compiling with .NET 2.0. Any ideas would be helpful.

+6
source share
5 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 constraint? It looks like you would use ToArray if it had an IList<T> . But it turns out that IEnumerable<T>.ToArray is an extension method defined on IEnumerable<T> that is implemented by IList<T> . So why don't you just use this?

+26
source

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

 IList list; var array = new List<string>(list).ToArray() 
+4
source

ToArray is an IEnumerable extension method, and IList implements IEnumerable. You can do this if you import it.

+3
source

One way or another, you will need to create an array and fill its contents with what is in the list. This is the most direct way to do this.

 var arr = new string[Your_List.Count] for(var ii = 0; ii < arr.Length; ii++){ arr[ii] = Your_List[ii]; } 
+1
source

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 just rude. Maybe his help.

0
source

Source: https://habr.com/ru/post/901214/


All Articles