如何将字符串添加到string []数组?没有.Add功能

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().

  • +1我会继续提供关于此主题的答案的链接.http://stackoverflow.com/questions/1168915/which-one-is-more-effecient-listint-or-int/1168922#1168922 (3认同)
  • “您不能将项目添加到数组中”-实际上您可以,请参见下文。 (2认同)

小智 103

或者,您可以调整阵列的大小.

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这是解决OP问题的(唯一)答案. (12认同)
  • `Array.Resize`*是*调整数组大小的正确方法.如果您在代码片段之前添加注释,说它很少是处理数组表示可调整大小的集合的情况的最佳方法,那么您将获得+1.:) (6认同)

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)

  • *`添加',而不是'添加'. (2认同)

小智 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)