C# ICollection<string> 到 string[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/328765/
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-03 23:23:17  来源:igfitidea点击:

ICollection<string> to string[]

c#genericscollections.net-2.0

提问by leora

I have a object of type ICollection<string>. What is the best way to convert to string[].

我有一个类型的对象ICollection<string>。转换为string[].

How can this be done in .NET 2?
How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?

如何在 .NET 2 中做到这一点?
如何在更高版本的 C# 中更清晰地完成这项工作,也许在 C# 3 中使用 LINQ?

采纳答案by AdrianoKF

You could use the following snippet to convert it to an ordinary array:

您可以使用以下代码段将其转换为普通数组:

string[] array = new string[collection.Count];
collection.CopyTo(array, 0);

That should do the job :)

那应该可以完成工作:)

回答by gimel

In the (trivial) case of ICollection<String>, use ToArray:

在 的(琐碎)情况下ICollection<String>,使用 ToArray:

String[] GetArray(ICollection<String> mycoll)
{
    return mycoll.ToArray<String>();
}

EDIT: with .Net 2.0, you can return the array with an extra List<String>:

编辑:使用.Net 2.0,您可以使用额外的返回数组List<String>

String[] GetArray(ICollection<String> mycoll)
{
    List<String> result = new List<String>(mycoll);
    return result.ToArray();
}

回答by CVertex

If you're using C# 3.0 and .Net framework 3.5, you should be able to do:

如果您使用 C# 3.0 和 .Net framework 3.5,您应该能够:

ICollection<string> col = new List<string>() { "a","b"};
string[] colArr = col.ToArray();

of course, you must have "using System.Linq;" at the top of the file

当然,你必须有“使用System.Linq;” 在文件顶部