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

发布于 2024-08-05 05:45:17 字数 375 浏览 7 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

何必那么矫情 2024-08-12 05:45:17

您无法将项目添加到数组中,因为它的长度是固定的。您正在寻找的是一个 List,稍后可以使用 list.ToArray() 将其转换为数组,例如

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

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(), e.g.

List<string> list = new List<string>();
list.Add("Hi");
String[] str = list.ToArray();
怪我入戏太深 2024-08-12 05:45:17

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

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

Alternatively, you can resize the array.

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
人疚 2024-08-12 05:45:17

使用列表来自 System.Collections.Generic

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

Use List<T> from System.Collections.Generic

List<string> myCollection = new List<string>();

…

myCollection.Add(aString);

Or, shorthand (using collection initialiser):

List<string> myCollection = new List<string> {aString, bString}

If you really want an array at the end, use

myCollection.ToArray();

You might be better off abstracting to an interface, such as IEnumerable, then just returning the collection.

Edit: If you must use an array, you can preallocate it to the right size (i.e. the number of FileInfo you have). Then, in the foreach loop, maintain a counter for the array index you need to update next.

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;
}
小草泠泠 2024-08-12 05:45:17

轻松

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

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();
手心的温暖 2024-08-12 05:45:17

如果我没记错的话是:

MyArray.SetValue(ArrayElement, PositionInArray)

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)
岁月蹉跎了容颜 2024-08-12 05:45:17

这是我在需要时添加到字符串的方法:

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

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);
}
等你爱我 2024-08-12 05:45:17

为什么不使用 for 循环而不是使用 foreach 呢?在这种情况下,您无法获取 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;
}

Why don't you use a for loop instead of using foreach. In this scenario, there is no way you can get the index of the current iteration of the foreach loop.

The name of the file can be added to the string[] in this way,

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;
}
居里长安 2024-08-12 05:45:17
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();
北风几吹夏 2024-08-12 05:45:17
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]
灰色世界里的红玫瑰 2024-08-12 05:45:17

此代码非常适合为 Android 中的微调器准备动态值数组:

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


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);

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()]);
萌面超妹 2024-08-12 05:45:17

using System.Linq; 添加对 Linq 的引用,并使用提供的扩展方法 Appendpublic static IEnumerable;附加(此 IEnumerable源,TSource 元素)
然后,您需要使用 .ToArray() 方法将其转换回 string[]

这是可能的,因为类型 string[] 实现了 IEnumerable,它还实现了以下接口:IEnumerableIEnumerableIComparableIComparableIConvertibleIEquatableICloneable

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

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

Adding a reference to Linq using System.Linq; and use the provided extension method Append: public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element)
Then you need to convert it back to string[] using the .ToArray() method.

It is possible, because the type string[] implements IEnumerable, it also implements the following interfaces: IEnumerable<char>, IEnumerable, IComparable, IComparable<String>, IConvertible, IEquatable<String>, ICloneable

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

Remember that ToArray allocates new array, therefore if you're adding more elements and you don't know how much of them you're going to have it's better to use List from System.Collections.Generic.

十二 2024-08-12 05:45:17

在这种情况下我不会使用数组。相反,我会使用 StringCollection。

using System.Collections.Specialized;

private StringCollection ColeccionDeCortes(string Path)   
{

    DirectoryInfo X = new DirectoryInfo(Path);

    FileInfo[] listaDeArchivos = X.GetFiles();
    StringCollection Coleccion = new StringCollection();

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion.Add( FI.Name );
    }
    return Coleccion;
}

I would not use an array in this case. Instead I would use a StringCollection.

using System.Collections.Specialized;

private StringCollection ColeccionDeCortes(string Path)   
{

    DirectoryInfo X = new DirectoryInfo(Path);

    FileInfo[] listaDeArchivos = X.GetFiles();
    StringCollection Coleccion = new StringCollection();

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion.Add( FI.Name );
    }
    return Coleccion;
}
笑脸一如从前 2024-08-12 05:45:17

要清除数组并同时使其元素数 = 0,请使用 this..

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

to clear the array and make the number of it's elements = 0 at the same time, use this..

System.Array.Resize(ref arrayName, 0);
一萌ing 2024-08-12 05:45:17

创建一个扩展:

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

Create an extention:

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

And use it as such:

foreach (FileInfo FI in listaDeArchivos)
{
    //Add the FI.Name to the Coleccion[] array, 
    Coleccion.Add(FI.Name);
}
为人所爱 2024-08-12 05:45:17

我会这样做:

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;

I would do it like this:

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文