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

我想转换FI。Name到字符串中,然后将其添加到数组中。我该怎么做呢?


当前回答

在这种情况下,我不会使用数组。相反,我将使用StringCollection。

using System.Collections.Specialized;

private StringCollection ColeccionDeCortes(string Path)   
{

    DirectoryInfo X = new DirectoryInfo(Path);

    FileInfo[] listaDeArchivos = X.GetFiles();
    StringCollection Coleccion = new StringCollection();

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion.Add( FI.Name );
    }
    return Coleccion;
}

其他回答

这段代码用于在Android中为spinner准备动态值数组:

    List<String> yearStringList = new ArrayList<>();
    yearStringList.add("2017");
    yearStringList.add("2018");
    yearStringList.add("2019");


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]

因为数组的长度是固定的,所以不能向数组中添加项。您要查找的是List<string>,稍后可以使用List . toarray()将其转换为数组,例如。

List<string> list = new List<string>();
list.Add("Hi");
String[] str = list.ToArray();

使用List<T> from System.Collections.Generic

List<string> myCollection = new List<string>();

…

myCollection.Add(aString);

或者,简写(使用集合初始化器):

List<string> myCollection = new List<string> {aString, bString}

如果您确实希望在结尾使用数组,请使用

myCollection.ToArray();

最好是将其抽象到接口,比如IEnumerable,然后直接返回集合。

编辑:如果你必须使用一个数组,你可以预先分配它到正确的大小(即FileInfo的数量)。然后,在foreach循环中,为接下来需要更新的数组索引维护一个计数器。

private string[] ColeccionDeCortes(string Path)
{
    DirectoryInfo X = new DirectoryInfo(Path);
    FileInfo[] listaDeArchivos = X.GetFiles();
    string[] Coleccion = new string[listaDeArchivos.Length];
    int i = 0;

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion[i++] = FI.Name;
        //Add the FI.Name to the Coleccion[] array, 
    }

    return Coleccion;
}

要清除该数组,同时使其元素的数量为0,请使用..

System.Array.Resize(ref arrayName, 0);