2013-10-16 31 views
4

此项目的背景。它开始作为一项简单的家庭作业,要求我存储5个邮政编码及其相应的城市。当用户在一个文本框中输入一个Zip代码时,就会返回一个相应的城市,同样的情况也可以完成。我编写了返回这些值的代码,但后来我决定将所有的邮政编码及其相应的城市存储在一个外部的.csv文件中,并将这些值存储在数组中,并将代码运行起来,因为如果值得这样做,它的价值矫枉过正!澄清,这不再是功课,只是为了了解更多关于在C#中使用外部文件。将.csv中的单独列拖到c中的单独数组中#

在下面的代码中,我调用了成功打开文件,现在我只需要帮助确定如何提取存储在两个单独列(一个用于城市,一个用于邮政编码)中的数据并存储它们在两个数组中由for循环执行。这是我现在的代码。你可以看到我怎么以前存储的其他值阵列和拉出来:

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

下面的数据是一个片段是什么在我的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 

等约46,000行。

我怎样才能拉zip和primary_city到两个单独的数组(我猜与一些“.Split”,“行),我的for循环可以操作?另外,如果有更好的方法去解决这个问题,请让我知道(但请务必留下解释,因为我想知道你来自哪里)。

+0

有很多样本的阅读CSV和几个完善的CSV阅读器。只要使用它们。如果你需要自己编写代码(假设它仍然是作业) - 请先尝试一下,然后用小的示例代码和详细的解释/错误文本/消息来提问什么不起作用。 –

+0

[C#的CSV解析器/阅读器?]的可能重复(http:// stackoverflow。com/questions/906841/csv-parser-reader-for-c) –

回答

3

不要创建两个单独的array.Create一个单独的类城市

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

我们从csv文件中读取数据

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

或者你可以做这

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); 
    } 
+0

我正在使用你的第二个建议,但我遇到了temp.ZipCode = int.Parse(s.Split(',')的问题[0]);线。我得到一个FormatException错误。我试图通过这个工作(它似乎不认为我把数字值为ZipCode)。有任何想法吗?一旦解决这个问题,我会将其标记为答案。 –

+0

@MarkP。在调试模式下,看看包含什么内容..大概可能有更多的1','在该字符串中.. – Anirudha

+0

@MarkP。检查编辑 – Anirudha

1

你可以试试这个:

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

} 
+0

我似乎有问题与HashList。 Visual Studio不能识别它,并且我已经初始化了所有正确的库(名称空间)...有什么想法? –

1

我张贴这个答案已经学到更多关于C#,因为我张贴了这个问题。阅读CSV时,有比String.Split()更好的选项。

.NET Framework已经有一个名为TextFieldParser的内置专用CSV解析器。

它位于Microsoft.VisualBasic.FileIO名称空间中。

不仅有很多边缘情况下String.Split()没有适当处理,但它也慢得多使用StreamReader

相关问题