簡體   English   中英

字符串[]到哈希表的數組,從字符串[] C#中添加鍵和值

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

我正在嘗試填充.txt文件中的string []數組的哈希表,我從目錄中讀取了.txt,但是無法填充foreach中的哈希表Im gettin錯誤=語法錯誤; 期望值。希望您能指導我一點。 第一語言。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM