このプロジェクトの背景。それは、5 つの郵便番号とそれに対応する都市を保存する必要がある簡単な宿題として始まりました。ユーザーが郵便番号をテキスト ボックスに入力すると、対応する都市が返されます。同様に、その逆も可能です。これらの値を返すコードを書きましたが、すべての郵便番号とそれに対応する都市を外部の .csv に保存し、それらの値を配列に保存してコードを実行することにしました。やり過ぎ!明確にするために、これはもはや宿題ではなく、C# での外部ファイルの使用について詳しく学ぶためのものです。
次のコードでは、ファイルを正常に開くために呼び出しました。ここで必要なのは、2 つの別々の列 (1 つは都市、もう 1 つは郵便番号) に格納されているデータを取得し、それらを 2 つの配列に格納する方法を理解することだけです。 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 を、for ループが操作できる 2 つの別個の配列 (".Split "," "行で推測しています) にプルするにはどうすればよいですか?
また、これについてもっと良い方法があれば教えてください(ただし、あなたがどこから来たのかを理解したいので、必ず説明を残してください)。