Search code examples
c#arraylisthashtable

String array to a hashtable


I'm trying to fill a HashTable with a string array from a .txt file.

Currently, I am reading the .txt file from a directory, but can´t fill the hashtable with a foreach loop.

I am getting the below:

Syntax error; value expected

Any help is much appreciated!

  static Hashtable GetHashtable()
  {
   // Create and return new Hashtable.
      Hashtable ht_rut = new Hashtable();
   //Create a string from all the text
      string rutcompleto = System.IO.File.ReadAllText(@"C:\datos rut.txt");
   //create an array from the string split by ,
      String[] rutArr = rutcompleto.Split(',');
   //create a int key for the hashtable
      int key = 1;
        
        foreach (var item in rutArr)
        {
            ht_rut.Add(key,rutArr[]);
            key = key + 1;
        }

        return ht_rut;
    }
 }

Solution

  • replace

    ht_rut.Add(key,rutArr[]);
    

    with

    ht_rut.Add(key,item);
    

    since you want to add the item instead of the whole array


    you could also solve this with linq:

    static Hashtable GetHashtable()
    {
        string[] rutcompleto = System.IO.File.ReadAllText(@"C:\datos rut.txt").Split(',');
        return new Hashtable(Enumerable.Range(1, rutcompleto.Count()).ToDictionary(x => x, x => rutcompleto[x-1]));
    }