我有一个类型为 ICollection<string>
的对象。如何最好地转换成 string[]
?
在 .NET 2 中应该如何做?
在 C# 3 中的较新版本中,如何更加简洁地做到这一点,也许可以使用 LINQ?
我有一个类型为 ICollection<string>
的对象。如何最好地转换成 string[]
?
在 .NET 2 中应该如何做?
在 C# 3 中的较新版本中,如何更加简洁地做到这一点,也许可以使用 LINQ?
您可以使用以下代码将它转换成普通数组:
string[] array = new string[collection.Count];
collection.CopyTo(array, 0);
那就可以了 :)
ICollection<string> col = new List<string>() { "a","b"};
string[] colArr = col.ToArray();
ICollection<String>
,请使用ToArray:String[] GetArray(ICollection<String> mycoll)
{
return mycoll.ToArray<String>();
}
编辑:使用.Net 2.0,您可以通过额外的List<String>
返回数组:
String[] GetArray(ICollection<String> mycoll)
{
List<String> result = new List<String>(mycoll);
return result.ToArray();
}
string[] array = new string[collection.Count];
,因为ICollection
有一个Count
属性。 - Paolo Moretti