【发布时间】:2015-07-22 14:24:20
【问题描述】:
我正在尝试创建一个文本文件,该文本文件进入一个类并将对象存储到数据字典中,然后创建一个允许我添加、编辑和删除等的 GUI。
我的文本文件的语法如下:
国家、GDP 增长、通货膨胀、贸易平衡、人类发展指数排名、主要贸易伙伴
例子:
- 美国,1.8,2,-3.1,4,[加拿大;英国;巴西]
- 加拿大,1.9,2.2,-2,6,[美国;中国]
无论如何,在创建 GUI 之前,我会先尝试使其在控制台中运行。国家出现在控制台中,但使用调试器中的步骤,我的对象数组和我的数据字典(如果我正确创建了数据字典)似乎正在存储,但是当它进入下一个国家时,它会覆盖前一个。我怎样才能做到这一点,以便所有国家都得到存储,而不仅仅是一个。如果这是有道理的,任何帮助将不胜感激。
我的代码:
class Program
{
static void Main(string[] args)
{
const int MAX_LINES_FILE = 50000;
string[] AllLines = new string[MAX_LINES_FILE];
int i = 0;
//reads from bin/DEBUG subdirectory of project directory
AllLines = File.ReadAllLines(@"C:\Users\Jack\Documents\countries.csv");
country[] newCountry = new country[30];
foreach (string line in AllLines)
{
if (line.StartsWith("Country")) //found first line - headers
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
newCountry[i] = new country();
newCountry[i].Country=(columns[0]);
newCountry[i].GDP=(columns[1]);
newCountry[i].Inflation=(columns[2]);
newCountry[i].TB =(columns[3]);
newCountry[i].HDI =(columns[4]);
newCountry[i].TP = (columns[5]);
Dictionary<object, string> CountryList = new Dictionary<object, string>();
CountryList.Add(newCountry[i].Country, newCountry[i].GDP + "," + newCountry[i].Inflation + "," + newCountry[i].TB + "," + newCountry[i].HDI + "," + newCountry[i].TP);
i++;
foreach (KeyValuePair<object, string> country in CountryList)
{
Console.WriteLine("Country = {0}, GDP = {1}",
country.Key, country.Value);
}
}
Console.ReadKey();
}
}
public static string[] headers { get; set; }
}
public class country
{
public string Country { get; set; }
public string GDP { get; set; }
public string Inflation { get; set; }
public string TB { get; set; }
public string HDI { get; set; }
public string TP { get; set; }
}
}
编辑:按照建议移动 CountryList 仍然遇到与 countryList 计数保持在 1 相同的问题。
我已经把它放在国家类的一个方法中了。
public static void addD(country a)
{
Dictionary<object, string> CountryList = new Dictionary<object, string>();
CountryList.Add(a.Country, a.GDP);
foreach (KeyValuePair<object, string> country in CountryList)
{
Console.WriteLine("Country = {0}, GDP = {1}", country.Key, country.Value);
}
}
并从这里调用它:
newCountry[i].TB =(columns[3]);
newCountry[i].HDI =(columns[4]);
newCountry[i].TP = (columns[5]);
country.addD(newCountry[i]);
【问题讨论】:
标签: c# arrays object dictionary data-structures