C# 如何将 System.Collections.Specialized.StringCollection 类型转换为 string[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13392411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:23:22  来源:igfitidea点击:

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

c#c#-4.0

提问by Annie

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

我的类库中的某些函数接受string[]作为参数。

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

我想将我的转换System.Collections.Specialized.StringCollectionstring[].

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

有没有可能用一个衬垫或者我必须用循环创建数组?

采纳答案by Habib

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

使用StringCollection.CopyTo(string[],index)将内容复制到字符串数组。所有 .Net 框架都支持这一点。

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

回答by yogi

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>();

回答by syazdani

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.

免责声明:我不知道它的性能特征是什么。