如何将一个字符串添加到字符串数组中?没有 .Add 函数。

288
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 转换为字符串并将其添加到我的数组中。我该怎么做?
15个回答

520

你无法向数组中添加项目,因为它的长度是固定的。你需要使用 List<string>,之后可以使用 list.ToArray() 将其转换为数组,例如:

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

3
+1 我会提供一个关于这个主题的答案链接。https://dev59.com/bHM_5IYBdhLWcg3w6X1e#1168922 - Sam Harwell
2
你不能向数组中添加项目 - 实际上可以,见下文。 - Alex Strickland

154

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

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

7
Array.Resize是调整数组大小的正确方法。如果你在代码片段前添加注释,说明它很少是处理表示可调整大小集合的情况的最佳方式,那么你就得到了+1。 :) - Sam Harwell
23
实际上,这是唯一一个完全解决了 OP 问题的答案。 - dialex
1
在 C# 8 中,您可以使用 array[^1] 来代替 array[array.Length -1] - nedstark179

74

请使用来自System.Collections.Generic的List<T>

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

我的方法只接收一个 string[] 数组,我不能使用 List<>。有没有办法让我用 Array 解决这个问题? - Sergio Tapia
1
使用 List<string>,当需要数组时,调用 ToArray 方法。 - Chris Dunaway

32

简单易用

// 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();

2
*Add,不是 add - chamberlainpi

10

如果我没记错的话,应该是:

MyArray.SetValue(ArrayElement, PositionInArray)

6

当需要时,我是这样添加字符串的:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}

4

为什么不使用for循环而是使用foreach?在这种情况下,你无法获取当前迭代的索引。

可以通过以下方式将文件名添加到string[]中,

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

  for (int i = 0; i < listaDeArchivos.Length; i++)
  {
     Coleccion[i] = listaDeArchivos[i].Name;
  }

  return Coleccion;
}

唯一的问题是:你必须知道listaDeArchivos的长度。如果你不知道(例如,如果它可能会改变,并且提前计算数量会很复杂,因为你的对象是嵌套模型或模型字段,可能填充/未填充),而你只想做string[] Coleccion;然后像int idx = 0; Coleccion[idx] = fileName; idx++;这样分配它,它会告诉你“使用了未赋值的本地变量' Coleccion'”。只是提醒任何想要使其更动态的人,有一个陷阱。 - vapcguy

2
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();

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

在这里解释为什么数组不是一个好的选择,建议使用List<>作为起点可能是个好主意。 - LueTm

1
添加对Linq的引用using System.Linq;并使用提供的扩展方法Append: public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element),然后您需要使用.ToArray()方法将其转换回string[]
这是可能的,因为类型string[]实现了IEnumerable接口,同时还实现了以下接口:IEnumerable<char>IEnumerableIComparableIComparable<String>IConvertibleIEquatable<String>ICloneable
using System.Linq;
public string[] descriptionSet new string[] {"yay"};
descriptionSet = descriptionSet.Append("hooray!").ToArray(); 

记住,ToArray会分配新的数组,因此如果您要添加更多元素并且不知道将有多少个元素,最好使用System.Collections.Generic中的List。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接