https://youtu.be/8QywTpeWZmg
public partial class DictionaryForm : Form
{
// Create a new dictionary of strings, with int keys.
Dictionary<string, int> valDic = new Dictionary<string, int>()
{
{ "Kim", 30 },
{ "Lee", 45 },
{ "Son", 7 },
{ "Park", 100 }
};
public DictionaryForm()
{
InitializeComponent();
}
private void DictionaryForm_Load(object sender, EventArgs e)
{
DictionList();
}
private void DictionList()
{
listView1.Items.Clear();
foreach(KeyValuePair<string, int> dic in valDic)
{
string[] mItem = new string[] { dic.Key, "" + dic.Value };
var listItem = new ListViewItem(mItem);
listView1.Items.Add(listItem);
}
var sortDic = radioButton1.Checked ? valDic.OrderBy(a => a.Key).ToDictionary(a => a.Key, a => a.Value) :
valDic.OrderBy(a => a.Value).ToDictionary(a => a.Key, a => a.Value);
listView2.Items.Clear();
foreach(KeyValuePair<string, int> dic in sortDic)
{
string[] mItem = new string[] { dic.Key, "" + dic.Value };
var listItem = new ListViewItem(mItem);
listView2.Items.Add(listItem);
}
}
private void button1_Click(object sender, EventArgs e)
{
int num;
bool numOk = int.TryParse(textBox2.Text, out num);
if(!numOk) return;
// method 1, ContainsKey can be check keys before adding
//if(valDic.ContainsKey(textBox1.Text))
// valDic[textBox1.Text] = num;
//else
// valDic.Add(textBox1.Text, num);
// method 2, if the new key is already in the dictionary the add method throws an exception
try
{
valDic.Add(textBox1.Text, num);
}
catch(ArgumentException)
{
valDic[textBox1.Text] = num;
}
DictionList();
}
private void button2_Click(object sender, EventArgs e)
{
// method 1
//if(!valDic.ContainsKey(textBox3.Text))
// textBox4.Text = "null";
//else
// textBox4.Text = "" + valDic[textBox3.Text];
// method 2
int value;
if(valDic.TryGetValue(textBox3.Text, out value))
textBox4.Text = "" + value;
else
textBox4.Text = "null";
}
private void button3_Click(object sender, EventArgs e)
{
valDic.Clear();
DictionList();
}
private void button4_Click(object sender, EventArgs e)
{
string selKey = listView1.SelectedItems[0].SubItems[0].Text;
if(!valDic.ContainsKey(selKey)) return;
valDic.Remove(selKey);
DictionList();
}
private void button5_Click(object sender, EventArgs e)
{
// To get the Key alone, use the Keys property.
Dictionary<string, int>.KeyCollection
valueKey = valDic.Keys;
textBox5.Text = "";
foreach(string value in valueKey)
textBox5.Text += (", " + value);
}
private void button6_Click(object sender, EventArgs e)
{
// To get the values alone, use the Values property.
Dictionary<string, int>.ValueCollection
valueVal = valDic.Values;
textBox6.Text = "";
foreach(int value in valueVal)
textBox6.Text += (", " + value);
}
}