简体   繁体   中英

How to add a string to a string[] array? There's no .Add function

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?

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() , eg

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

Alternatively, you can resize the array.

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

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

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

如果我没记错的话是:

MyArray.SetValue(ArrayElement, PositionInArray)

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

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;
}
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();

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

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

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

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;
}
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM