【问题标题】:String [] Array to a hashtable, adding a key and value from the string [] C#String [] 数组到哈希表,从字符串 [] C# 中添加键和值
【发布时间】:2016-07-08 05:59:23
【问题描述】:

我正在尝试使用 .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;
    }
 }

【问题讨论】:

    标签: c# arraylist hashtable


    【解决方案1】:

    替换

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

    【讨论】:

    • 这很好,我的查询是错误的,所以谢谢,
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多