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


当前回答

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

其他回答

使用System.Linq添加对Linq的引用;并使用提供的扩展方法追加:公共静态IEnumerable<TSource>追加<TSource>(此IEnumerable<TSource>源,TSource元素) 然后你需要使用. toarray()方法将它转换回字符串[]。

这是可能的,因为类型string[]实现了IEnumerable,它也实现了以下接口:IEnumerable<char>, IEnumerable, IComparable, IComparable< string >, IConvertible, IEquatable< string >, ICloneable

using System.Linq;
public string[] descriptionSet new string[] {"yay"};
descriptionSet = descriptionSet.Append("hooray!").ToArray(); 

请记住,ToArray分配新的数组,因此,如果你添加更多的元素,你不知道你将有多少,最好使用List from System.Collections.Generic。

或者,您可以调整数组的大小。

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";

如果我没记错的话是:

MyArray.SetValue(ArrayElement, PositionInArray)

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

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

我会这样做:

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;