简体   繁体   中英

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

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.

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?

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

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

ToArray is an extension method of IEnumerable, and IList implement IEnumerable. You can do it if you import that.

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];

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM