Ser*_*pia 205 c# arrays long-filenames
private string[] ColeccionDeCortes(string Path)
{
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion;
foreach (FileInfo FI in listaDeArchivos)
{
//Add the FI.Name to the Coleccion[] array,
}
return Coleccion;
}
Run Code Online (Sandbox Code Playgroud)
我想将其转换FI.Name为字符串,然后将其添加到我的数组中.我怎样才能做到这一点?
Sau*_*tka 366
您无法将项添加到数组中,因为它具有固定的长度,您要查找的是a List<string>,以后可以使用它转换为数组list.ToArray().
小智 103
或者,您可以调整阵列的大小.
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
Run Code Online (Sandbox Code Playgroud)
Ada*_*ght 59
使用System.Collections.Generic中的List <T>
List<string> myCollection = new List<string>();
…
myCollection.Add(aString);
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一个数组,请使用
List<string> myCollection = new List<string> {aString, bString}
Run Code Online (Sandbox Code Playgroud)
你可能最好抽象到一个接口,比如IEnumerable,然后只返回集合.
编辑:如果必须使用数组,则可以将其预分配到正确的大小(即您拥有的FileInfo的数量).然后,在foreach循环中,为下一步需要更新的数组索引维护一个计数器.
myCollection.ToArray();
Run Code Online (Sandbox Code Playgroud)
Nol*_*osi 27
EAZY
// Create list
var myList = new List<string>();
// Add items to the list
myList.Add("item1");
myList.Add("item2");
// Convert to array
var myArray = myList.ToArray();
Run Code Online (Sandbox Code Playgroud)
小智 10
如果我没弄错的话是:
MyArray.SetValue(ArrayElement, PositionInArray)
Run Code Online (Sandbox Code Playgroud)
小智 5
这是我在需要时添加到字符串的方式:
string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
myList[i] = string.Format("List string : {0}", i);
}
Run Code Online (Sandbox Code Playgroud)