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

C#ArraysLong Filenames

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Alternatively, you can resize the array.

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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

Solution 9 - C#

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

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

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.

Solution 11 - C#

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

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergio TapiaView Question on Stackoverflow
Solution 1 - C#Saulius ValatkaView Answer on Stackoverflow
Solution 2 - C#Siebe TolsmaView Answer on Stackoverflow
Solution 3 - C#Adam WrightView Answer on Stackoverflow
Solution 4 - C#NoloMokgosiView Answer on Stackoverflow
Solution 5 - C#Stefan NicolovView Answer on Stackoverflow
Solution 6 - C#kittugaduView Answer on Stackoverflow
Solution 7 - C#Sarath RachuriView Answer on Stackoverflow
Solution 8 - C#xcudView Answer on Stackoverflow
Solution 9 - C#Taras VovkovychView Answer on Stackoverflow
Solution 10 - C#proximabView Answer on Stackoverflow
Solution 11 - C#user175116View Answer on Stackoverflow
Solution 12 - C#DeyaEldeenView Answer on Stackoverflow
Solution 13 - C#Konstantin LapeevView Answer on Stackoverflow
Solution 14 - C#Gregory LiénardView Answer on Stackoverflow
Solution 15 - C#ItsYeBoi2016View Answer on Stackoverflow