【问题标题】:Textfile to class to Data Dictionary文本文件分类到数据字典
【发布时间】: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


    【解决方案1】:

    试试这个代码,我已经清理了它并添加了 cmets,因为它很难使用。

           static void Main(string[] args)
        {
            // Initalize the loop iterator
            int i = 0;
    
            // Initalize a list of country data
            country[] newCountry = new country[30];
    
            // Initialize a list of countries
            Dictionary<object, string> countryList = new Dictionary<object, string>();
    
            // Read all the lines from the file
            string[] fileLines = File.ReadAllLines(@"C:\Users\Jack\Documents\countries.csv");
    
            // For each line in the file
            foreach (string line in fileLines)
            {
                // Check if the line is a header
                if (line.StartsWith("Country"))
                {
                    headers = line.Split(',');
                }
                else
                {
                    // Split the text data
                    string[] columns = line.Split(',');
    
                    // Initalize a new country
                    newCountry[i] = new country
                    {
                        Country = columns[0],
                        GDP = columns[1],
                        Inflation = columns[2],
                        TB = columns[3],
                        HDI = columns[4],
                        TP = columns[5]
                    };
    
                    countryList.Add(newCountry[i].Country, string.Format("{0},{1},{2},{3},{4}", newCountry[i].GDP, newCountry[i].Inflation, newCountry[i].TB, newCountry[i].HDI, newCountry[i].TP));
                    i++;
                }
            }
    
            // The process is done show the data
            foreach (KeyValuePair<object, string> country in countryList)
            {
                Console.WriteLine("Country = {0}, GDP = {1}", country.Key, country.Value);
            }
    
            // Wait for the user key
            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; }
    
        }
    

    进一步更新为什么还要使用国家集合?下面是一个更好的方法

    static void Main(string[] args)
    {
        // Initalize a list of country data
        List<country> countryList = new List<country>();
    
        // Read all the lines from the file
        string[] fileLines = File.ReadAllLines(@"countries.csv");
    
        // For each line in the file
        foreach (string line in fileLines)
        {
            // Check if the line is a header
            if (line.StartsWith("Country"))
            {
                headers = line.Split(',');
            }
            else
            {
                // Split the text data
                string[] columns = line.Split(',');
    
                // Initalize a new country
                country fileCountry = new country
                {
                    Country = columns[0],
                    GDP = columns[1],
                    Inflation = columns[2],
                    TB = columns[3],
                    HDI = columns[4],
                    TP = columns[5]
                };
    
                countryList.Add(fileCountry);
            }
        }
    
        // The process is done show the data
        foreach (country country in countryList)
        {
            Console.WriteLine("Country = {0}, GDP = {1}", country.Country, country.GDP);
        }
    
        // Wait for the user key
        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; }
    
    }
    

    根据问题进行第二次更新,列表框是开始使用 win UI 控件的好方法,我添加了下面的示例。添加一个名为 button1 的按钮和一个名为

    的列表框控件
    // List holding all the country data
            private List<country> countryList;
    
            /// <summary>
            /// Handle the button click
            /// </summary>
            /// <param name="sender">See MSDN</param>
            /// <param name="e">See MSDN</param>
            private void button1_Click(object sender, EventArgs e)
            {
                // Initalize a list of country data
                this.countryList = new List<country>();
    
                // Set the display text to the display property of the country class
                this.listBox1.DisplayMember = "Display";
    
                // Set the value of the list box item to the current country
                this.listBox1.ValueMember = "Country";
    
                // Populate the data
                this.PopulateData();
    
                // Set the list box datasource
                this.listBox1.DataSource = this.countryList;
            }
    
            /// <summary>
            /// Gets the country data from the csv file
            /// </summary>
            private void PopulateData()
            {
                // Read all the lines from the file
                string[] fileLines = File.ReadAllLines(@"countries.csv");
    
                // For each line in the file
                foreach (string line in fileLines)
                {
                    // Check if the line is a header
                    if (line.StartsWith("Country"))
                    {
                        headers = line.Split(',');
                    }
                    else
                    {
                        // Split the text data
                        string[] columns = line.Split(',');
    
                        // Initalize a new country
                        country fileCountry = new country
                        {
                            Country = columns[0],
                            GDP = columns[1],
                            Inflation = columns[2],
                            TB = columns[3],
                            HDI = columns[4],
                            TP = columns[5]
                        };
    
                        this.countryList.Add(fileCountry);
                    }
                }
    
                // The process is done show the data
                foreach (country country in this.countryList)
                {
                    Console.WriteLine(country.Display);
                }
            }
    
            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; }
    
                /// <summary>
                /// Formats the display string for the country 
                /// </summary>
                public string Display
                {
                    get
                    {
                        return string.Format("Country = {0}, GDP = {1}", this.Country, this.GDP);
                    }
                }
            }
    

    【讨论】:

    • 太棒了!你是圣人。我想我必须使用 Country 选择,但请记住另一个以供将来参考。在我不可避免地再次陷入困境之前快速提问。我现在要把它变成一个简单的 GUI。您认为最好将输出移动到列表框中吗?如果是这样,我将如何将字典或列表(如您的其他建议)添加到列表框中?还是你会建议别的?
    • @MysteryMan113 我已更新我的答案以包含列表框的代码,如果这已回答您的问题,请标记为已回答。
    【解决方案2】:

    您在 foreach 块中声明 CountryList,因此它在每次迭代结束时失去作用域,并且您在下一次迭代时从头开始重新创建它。您需要在 foreach 块之外或作为类的成员声明它。

    【讨论】:

    • 感谢您的回复,将 CountryList 从 foreach 块移到 country 类中自己的方法,但 countrylist 计数仍保持在 1
    • 您能否详细说明一下您说您将其移至国家/地区类中自己的方法时的意思?该方法有什么作用?你怎么称呼它?
    • 字典 CountryList = new Dictionary();此代码将创建一个新的国家/地区列表并清除您已有的所有记录。这需要在流程开始时完成一次,而不是每次添加国家/地区时。
    猜你喜欢
    • 2018-12-25
    • 2021-11-25
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多