String [] Array to a hashtable,从string [] C#中添加一个键和值

String [] Array to a hashtable, adding a key and value from the string [] C#

我正在尝试用 .txt 文件中的字符串 [] 数组填充哈希表, 我从目录中读取了 .txt,但无法用 foreach 填充哈希表 我得到一个错误 = 语法错误;预期价值 希望你能指导我一点。 第一语言。

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

替换

ht_rut.Add(key,rutArr[]);

ht_rut.Add(key,item);

因为您想添加项目而不是整个数组


你也可以用 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]));
}

rutArr[] 不是有效的 C# 语法,您需要使用 rutArr[index] 或 foreach 中的迭代变量 item:

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