Как упростить программу? - C#
Формулировка задачи:
помогите с кодом пожалуйста. имеется повторяющийся код. нужно как то его упростить, я пока учусь и мало чего знаю. предполагаю что это делается через функцию. помогите, заранее спасибо
public void button3_Click(object sender, EventArgs e)
{
string word = richTextBox1.Text;
if (comboBox1.Text == "english")
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string path = "ru-en.txt";
StreamReader sr = new StreamReader(path, Encoding.Default);
string[] split;
while (!sr.EndOfStream)
{
split = sr.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (!dictionary.ContainsKey(split[0]))
{
dictionary.Add(split[0], split[1]);
}
}
sr.Close();
sr.Dispose();
richTextBox2.Text = dictionary[word];
}
if (comboBox1.Text == "italian")
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string path = "ru-itl.txt";
StreamReader sr = new StreamReader(path, Encoding.Default);
string[] split;
while (!sr.EndOfStream)
{
split = sr.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (!dictionary.ContainsKey(split[0]))
{
dictionary.Add(split[0], split[1]);
}
}
sr.Close();
sr.Dispose();
richTextBox2.Text = dictionary[word];
}
if (comboBox1.Text == "french")
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string path = "ru-fr.txt";
StreamReader sr = new StreamReader(path, Encoding.Default);
string[] split;
while (!sr.EndOfStream)
{
split = sr.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (!dictionary.ContainsKey(split[0]))
{
dictionary.Add(split[0], split[1]);
}
}
sr.Close();
sr.Dispose();
richTextBox2.Text = dictionary[word];
}
}Решение задачи: «Как упростить программу?»
textual
Листинг программы
public void button3_Click(object sender, EventArgs e)
{
string word = richTextBox1.Text, path;
if (comboBox1.Text == "english") path = "ru-en.txt";
else if (comboBox1.Text == "italian") path = "ru-itl.txt";
else if (comboBox1.Text == "french") path = "ru-fr.txt";
else return;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
string[] split;
while (!sr.EndOfStream)
{
split = sr.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (!dictionary.ContainsKey(split[0]))
{
dictionary.Add(split[0], split[1]);
}
}
}
richTextBox2.Text = dictionary[word];
}