public partial class Form1 : Form
{
public static Dictionary<string,string> contactList = new Dictionary<string,string>();
public Form1()
{
InitializeComponent();
Text = "My Telephone Directory";
}
private void txtAdd_Click(object sender, EventArgs e)
{
String name = txtName.Text;
String teleNo = txtTelephone.Text;
contactList.Add(name,teleNo);
txtContactList.Text = "Added " + name;
}
private void txtClear_Click(object sender, EventArgs e)
{
txtContactList.Text = " ";
}
private void txtList_Click(object sender, EventArgs e)
{
String contactLists="";
foreach (KeyValuePair<string,string> kvp in contactList)
{
contactLists += "Name: " + contactList.Keys.ToString()+ " Phone No: " + contactList.Values + Environment.NewLine;
}
txtContactList.Text = contactLists;
}
private void txtSearch_Click(object sender, EventArgs e)
{
String contactLists = "";
foreach (KeyValuePair<string, string> kvp in contactList)
{
contactLists += "Name: " + contactList.Keys.ToString() + " Phone No: " + contactList.Values + Environment.NewLine;
if (contactList.Keys.ToString() == txtName.Text)
{
contactLists += "Name: " + contactList.Keys.ToString() + " Phone No: " + contactList.Values.ToString() + Environment.NewLine;
}
txtContactList.Text = contactLists;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
}
}
我无法枚举字典,请参阅txtList_Click事件处理程序。
如果我正在做什么,我得到System.Collections.Generic.Dictionary 2+KeyCollection[System.String,System.String] Phone No: System.Collections.Generic.Dictionary
2 + ValueCollection [System.String,System.String]。
如果我做contactList.Key就像我应该得到System.Collections.Generic.Dictionary
答案 0 :(得分:1)
迭代字典并构建taskkill /f /im firefox.exe
字符串
要迭代contactLists
并构建字符串,只需使用您在Dictionary
中指定的KeyValuePair
变量(kvp
):
foreach
但是,在循环is inefficient中连接字符串 foreach (KeyValuePair<string, string> kvp in contactList)
{
contactLists += "Name: " + kvp.Key
+ " Phone No: " + kvp.Value + Environment.NewLine;
...
。 contactLists
在这里会有所帮助,或者,您可以简单地计算出每个键值对&#34; string&#34;而不是循环。使用Linq Select,然后StringBuilder
。
Join
重新搜索词典
使用Dictionary(或HashSet)的一个好处是它提供了索引/键控查找,因此您不需要通过手动比较键来迭代整个集合来查找元素。因此,如果您按照此人的姓名键入了电话号码,这将是一种更典型的用法:
var contactLists =
string.Join(Environment.NewLine,
contactList.Select(cl => string.Format("Name: {0} Phone No: {1}",
cl.Key, cl.Value)));
为了使其更加强大,您需要先检查密钥是否存在,例如使用 var searchPhone = contactList[txtName.Text];
或ContainsKey
:
TryGetValue
答案 1 :(得分:1)
您正在调用集合对象上的ToString()
方法,而不是特定的键和值对。试试这个:
foreach (KeyValuePair<string,string> kvp in contactList)
{
contactLists += "Name: " + kvp.Key + " Phone No: " + kvp.Value + Environment.NewLine;
}