How to add a string to a string[] array? There'

2019-01-10 06:07发布

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

I'd like to convert the FI.Name to a string and then add it to my array. How can I do this?

13条回答
我命由我不由天
2楼-- · 2019-01-10 06:34
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();
查看更多
萌系小妹纸
3楼-- · 2019-01-10 06:36

This is how I add to a string when needed:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}
查看更多
The star\"
4楼-- · 2019-01-10 06:39

Alternatively, you can resize the array.

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
查看更多
Root(大扎)
5楼-- · 2019-01-10 06:42

This code works great for preparing the dynamic values Array for spinner in Android:

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


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);
查看更多
小情绪 Triste *
6楼-- · 2019-01-10 06:44

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)
查看更多
叛逆
7楼-- · 2019-01-10 06:46

You can't add items to an array, since it has fixed length, what you're looking for is a List<string>, which can later be turned to an array using list.ToArray().

查看更多
登录 后发表回答