2014-06-10 32 views
-3

我在它與該信息的文本文件:從文本文件創建在C#中的字典中定義的結構

01 Index 
home 
about 

02 Home 
first 
second 
third 

以數字開頭的行表示一個鍵並遵循它,直到一個空行,是值。

我想要一個字典對象,其中第一行的鍵和後面的行作爲字符串數組表示。

像這樣:

key = "01 Index" 
value = string[] 

其中陣列中的值將是:

string[0] = "home" 
string[1] = "about" 

下一個關鍵將是 「02家」 和其下面的行作爲字符串[]。

此方法讀取文本文件:

string[] ReadFileEntries(string path) 
{ 
    return File.ReadAllLines(path); 
} 

這使所有的線,8上面的示例中,該字符串[]其中第四線將是空白行英寸

如何從此創建所需的字典?

在此先感謝。

問候。

+0

你有什麼錯誤? – quantdev

+1

沒有錯誤,我在ReadFileEntries方法後卡住了。 – Codehelp

+0

不明白爲什麼這被標記爲關閉? – Codehelp

回答

0

解析文件到,比方說,Dictionary<String, String[]>你可以做財產以後這樣的:

Dictionary<String, String[]> data = new Dictionary<String, String[]>(); 

    String key = null; 
    List<String> values = new List<String>(); 

    foreach (String line in File.ReadLines(path)) { 
    // Skip blank lines 
    if (String.IsNullOrEmpty(line)) 
     continue; 

    // Check if it's a key (that should start from digit) 
    if ((line[0] >= '0' && line[0] <= '9')) { // <- Or use regular expression 
     if (!Object.ReferenceEquals(null, key)) 
     data.Add(key, values.ToArray()); 

     key = line; 
     values.Clear(); 

     continue; 
    } 

    // it's a value (not a blank line and not a key) 
    values.Add(line); 
    } 

    if (!Object.ReferenceEquals(null, key)) 
    data.Add(key, values.ToArray()); 
0

這應該做你想要做的事。有改進的餘地,我建議重構一下。

var result = new Dictionary<string, string[]>(); 

var input = File.ReadAllLines(@"c:\temp\test.txt"); 
var currentValue = new List<string>(); 
var currentKey = string.Empty; 

foreach (var line in input) 
{ 
    if (currentKey == string.Empty) 
    { 
     currentKey = line; 
    } 
    else if (!string.IsNullOrEmpty(line)) 
    { 
     currentValue.Add(line); 
    } 

    if (string.IsNullOrEmpty(line)) 
    { 
     result.Add(currentKey, currentValue.ToArray()); 
     currentKey = string.Empty; 
     currentValue = new List<string>(); 
    } 
} 

if (currentKey != string.Empty) 
{ 
    result.Add(currentKey, currentValue.ToArray()); 
} 
0

我們聲明性質的以這種方式的字典:

Dictionary<string, string[]> myDict = new Dictionary<string, string[]>() 

來填充它,我們這樣做:

myDict.Add(someString, someStringArray[]); 

我覺得這樣的事情會做到這一點:

string[] TheFileAsAnArray = ReadFileEntries(path); 
Dictionary<string, string[]> myDict = new Dictionary<string, string[]>() 

string key = ""; 
List<string> values = new List<string>(); 
for(int i = 0; i <= TheFileAsAnArray.Length; i++) 
{ 

    if(String.isNullOrEmpty(TheFileAsAnArray[i].Trim())) 
    { 
      myDict.Add(key, values.ToArray()); 
      key = String.Empty; 
      values = new List<string>(); 

    } 
    else 
    { 
     if(key == String.Empty) 
      key = TheFileAsAnArray[i]; 
     else 
      values.Add(TheFileAsAnArray[i]); 
    } 
} 
相關問題