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到字符串中,然后将其添加到数组中。我该怎么做呢?


当前回答

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

其他回答

我会这样做:

DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion = new String[] { };

foreach (FileInfo FI in listaDeArchivos)
{
    Coleccion = Coleccion.Concat(new string[] { FI.Name }).ToArray();
}

return Coleccion;
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();

创建一个扩展:

public static class TextFunctions
{
    public static string [] Add (this string[] myArray, string StringToAdd)
    {
          var list = myArray.ToList();
          list.Add(StringToAdd);
          return list.ToArray();
    }
}

并这样使用它:

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

这段代码用于在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()]);