此项目的背景。它开始作为一项简单的家庭作业,要求我存储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循环可以操作?另外,如果有更好的方法去解决这个问题,请让我知道(但请务必留下解释,因为我想知道你来自哪里)。
有很多样本的阅读CSV和几个完善的CSV阅读器。只要使用它们。如果你需要自己编写代码(假设它仍然是作业) - 请先尝试一下,然后用小的示例代码和详细的解释/错误文本/消息来提问什么不起作用。 –
[C#的CSV解析器/阅读器?]的可能重复(http:// stackoverflow。com/questions/906841/csv-parser-reader-for-c) –