简体   繁体   English

将单独的列从.csv拉入c#中的单独数组

[英]Pull separate columns from .csv into separate arrays in c#

Background on this project. 这个项目的背景。 It started as a simple homework assignment that required me to store 5 zip codes and their corresponding cities. 它起初是一个简单的家庭作业,要求我存储5个邮政编码及其相应的城市。 When a user puts a Zip code in a textbox, a corresponding city is returned, and likewise the opposite can be done. 当用户将Zip代码放入文本框中时,返回相应的城市,同样可以进行相反的操作。 I wrote the code to return these values, but then I decided I wanted to store ALL zip codes and their corresponding Cities in an external .csv, and store those values in arrays and run the code off that because if its worth doing, its worth overdoing! 我编写代码来返回这些值,但后来我决定将所有邮政编码及其相应的城市存储在外部.csv中,并将这些值存储在数组中并运行代码,因为如果它值得做,那么它的价值矫枉过正! To clarify, this is no longer for homework, just to learn more about using external files in C#. 为了澄清,这不再是作业,只是为了更多地了解在C#中使用外部文件。

In the following code, I have called to open the file successfully, now I just need help in figuring out how to pull the data that is stored in two separate columns (one for city, one for zip code) and store them in two arrays to be acted upon by the for loop. 在下面的代码中,我已经调用成功打开文件,现在我只需要帮助搞清楚如何提取存储在两个单独列中的数据(一个用于城市,一个用于邮政编码)并将它们存储在两个数组中由for循环操作。 Here is the code I have now. 这是我现在的代码。 You can see how I have previously stored the other values in arrays and pulled them out: 您可以看到我以前如何将其他值存储在数组中并将其拉出:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnConvert2City_Click(object sender, EventArgs e)
    {
        try
        {
            string dir = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location);

            string path = dir + @"\zip_code_database_edited.csv";
            var open = new StreamReader(File.OpenRead(path));

            int EnteredZipcode = Convert.ToInt32(txtZipcode.Text.Trim());
            string result = "No Cities Found";

            string[] Cities = new String[5] { "FLINTSTONE", "JAMAICA", "SCHENECTADY", "COTTONDALE", "CINCINNATI" };
            int[] Zipcode = new int[5] { 30725, 11432, 12345, 35453, 45263 };

            for (int i = 0; i <= Zipcode.Length - 1; i++)
            {
                if (Zipcode[i] == EnteredZipcode)
                {
                    result = Cities[i];
                    break;
                }
            }
            string DisplayState = result;
            txtCity.Text = DisplayState;
        }
        catch (FormatException)
        {
            MessageBox.Show("Input must be numeric value.");
        }
        catch (OverflowException)
        {
            MessageBox.Show("Zipcode to long. Please Re-enter");
        }
    }

    private void btnConvert2Zipcode_Click(object sender, EventArgs e)
    {
        string dir = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location);

        string path = dir + @"\zip_code_database_edited.csv";
        var open = new StreamReader(File.OpenRead(path));

        String EnteredCity = txtCity.Text.ToUpper();
        string result = "No Zipcode Found";

        string[] Cities = new String[5] { "FLINTSTONE", "JAMAICA", "SCHENECTADY", "COTTONDALE", "CINCINNATI" };
        int[] Zipcode = new int[5] { 30725, 11432, 12345, 35453, 45263 };

        for (int i = 0; i <= Cities.Length - 1; i++)
        {
            if (Cities[i] == EnteredCity)
            {
                result = Convert.ToString(Zipcode[i]);
                break;
            }
        }           
        string DisplayZip = result;
        txtZipcode.Text = DisplayZip;
    }       
}

The following data is a snippet of what the data in my excel .csv looks like: 以下数据是我的excel .csv中的数据的片段:

zip,primary_city
44273,Seville
44274,Sharon Center
44275,Spencer
44276,Sterling
44278,Tallmadge
44280,Valley City
44281,Wadsworth
44282,Wadsworth
44285,Wayland

And so on for about 46,000 rows. 等等约46,000行。

How can I pull the zip and the primary_city into two separate arrays (I'm guessing with some ".Split "," "line) that my for-loop can operate on? 我怎样才能将zip和primary_city拉成两个独立的数组(我猜的是一些“.Split”,“”行)我的for-loop可以操作?

Also, if there are better ways to go about this, please let me know (but be sure to leave an explanation as I want to understand where you are coming from). 另外,如果有更好的方法可以解决这个问题,请告诉我(但请务必留下解释,因为我想了解您的来源)。

Don't create two separate array.Create a separate class for city 不要创建两个单独的数组。为城市创建一个单独的类

class City
{
    public string Name{get;set;}
    public int ZipCode{get;set;}
}

Now to read the data from that csv file 现在从该csv文件中读取数据

List<City> cities=File.ReadAllLines(path)
                      .Select(x=>new City
                         {
                              ZipCode=int.Parse(x.Split(',')[0]),
                              Name=x.Split(',')[1]
                         }).ToList<City>();

Or you can do this 或者你可以做到这一点

   List<City> cities=new List<City>();
   foreach(String s in File.ReadAllLines(path))
   {
       City temp=new City();
       temp.ZipCode=int.Parse(s.Split(',')[0]);
        temp.Name=s.Split(',')[1];
       cities.Add(temp);
   }

You can try this: 你可以试试这个:

    string dir = System.IO.Path.GetDirectoryName(
            System.Reflection.Assembly.GetExecutingAssembly().Location);

    string path = dir + @"\zip_code_database_edited.csv";
    var open = new StreamReader(File.OpenRead(path));
    var cities = new HashList<string>();
    var zipCodes = new HashList<int>();
    var zipAndCity = new string[2];
    string line = string.Empty;
    using (open)
{
        while ((line = reader.ReadLine()) != null)
        {
            zipAndCity = line.Split(",");
                zipCodes.Add(int.Parse(zipAndCity[0]));
                cities.Add(zipAndCity[1]);   
        }

}

I am posting this answer having learned much more about C# since I posted this question. 自从我发布这个问题后,我发布了关于C#的更多信息。 When reading a CSV, there are better options than String.Split() . 读取CSV时,有比String.Split()更好的选项。

The .NET Framework already has a built-in dedicated CSV parser called TextFieldParser . .NET Framework已经有一个名为TextFieldParser的内置专用CSV解析器。

It's located in the Microsoft.VisualBasic.FileIO namespace. 它位于Microsoft.VisualBasic.FileIO命名空间中。

Not only are there many edge cases that String.Split() is not properly equipped to handle, but it's also much slower to use StreamReader . 不仅有很多边缘情况, String.Split()没有正确配置来处理,但使用StreamReader也慢得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM