Vlad
Vlad

Reputation: 21

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

Upvotes: 0

Views: 6801

Answers (2)

fubo
fubo

Reputation: 45947

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

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30022

rutArr[] is not a valid C# syntax, you need to use rutArr[index] or the iteration variable inside foreach item:

foreach (var item in rutArr)
{
    ht_rut.Add(key, item);
    key = key + 1;
}

Upvotes: 0

Related Questions