简体   繁体   中英

How to convert type System.Collections.Specialized.StringCollection to string[]

Some functions in my class library accepts string[] as parameter.

I want to convert my System.Collections.Specialized.StringCollection to string[] .

Is it possible with some one liner or I have to create array with loop?

Use StringCollection.CopyTo(string[],index) to copy the contents to string array. This is supported in all .Net frameworks.

System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
sc.Add("Test");
sc.Add("Test2");

string[] strArray = new string[sc.Count];
sc.CopyTo(strArray,0);

Try this

System.Collections.Specialized.StringCollection strs = new  System.Collections.Specialized.StringCollection();
strs.Add("blah"); 
strs.Add("blah"); 
strs.Add("blah"); 

string[] strArr = strs.Cast<string>().ToArray<string>();

This does the trick:

System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
/*sc.Add("A");
sc.Add("B");*/
string[] asArray = sc.Cast<string>().ToArray();

Disclaimer: I have no idea what the performance characteristics of this are.

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