Sergio Tapia
Sergio Tapia

Reputation: 41228

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?

Upvotes: 296

Views: 1055829

Answers (15)

Gregory Liénard
Gregory Liénard

Reputation: 1781

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

Upvotes: 0

proximab
proximab

Reputation: 2473

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.

Upvotes: 1

ItsYeBoi2016
ItsYeBoi2016

Reputation: 3

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;

Upvotes: -1

Saulius Valatka
Saulius Valatka

Reputation: 7207

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

Upvotes: 535

Adam Wright
Adam Wright

Reputation: 49386

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

Upvotes: 74

kittugadu
kittugadu

Reputation: 61

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

Upvotes: 6

Konstantin Lapeev
Konstantin Lapeev

Reputation: 21

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

Upvotes: 2

NoloMokgosi
NoloMokgosi

Reputation: 1718

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

Upvotes: 32

DeyaEldeen
DeyaEldeen

Reputation: 11857

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

Upvotes: 0

Taras Vovkovych
Taras Vovkovych

Reputation: 4252

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

Upvotes: 1

user175116
user175116

Reputation:

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

Upvotes: 0

Sarath Rachuri
Sarath Rachuri

Reputation: 2116

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

Upvotes: 4

Stefan Nicolov
Stefan Nicolov

Reputation: 109

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)

Upvotes: 10

xcud
xcud

Reputation: 14732

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

Upvotes: 2

Siebe Tolsma
Siebe Tolsma

Reputation:

Alternatively, you can resize the array.

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

Upvotes: 157

Related Questions