ICollection <string>到string []

leo*_*ora 17 c# generics collections .net-2.0

我有一个类型的对象ICollection<string>.什么是转换的最佳途径string[].

如何在.NET 2中完成?
如何在C#的后续版本中更清洁,也许在C#3中使用LINQ?

Adr*_*oKF 32

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

string[] array = new string[collection.Count];
collection.CopyTo(array, 0);
Run Code Online (Sandbox Code Playgroud)

那应该做的工作:)


CVe*_*tex 8

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

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

当然,你必须"使用System.Linq;" 在文件的顶部

  • 他要求ICollection <string> (4认同)

gim*_*mel 6

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

String[] GetArray(ICollection<String> mycoll)
{
    return mycoll.ToArray<String>();
}
Run Code Online (Sandbox Code Playgroud)

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

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