我有词典:
{3,null,4,null,null}
这样填充:
public Dictionary<int, string> jobs = new Dictionary<int, string>();
我尝试在作业词典中添加值:
this.jobs.Add(1, "Усі види підземних робіт, відкриті гірничі роботи.");
如您所见,我添加到列表值foreach (KeyValuePair<int, string> kvp in jobs.get()) {
listBox1.Items.Add(String.Format("№{0} - ({1})", kvp.Key, kvp.Value.ToString()));
}
。但是如何设置密钥?
答案 0 :(得分:1)
以下是pm100建议的示例:
创建一个用于绑定列表框的模型类,如下所示:
class Job
{
public int Key { get; set; }
public string Description { get; set; }
public override string ToString()
{
return String.Format("№{0} - ({1})", this.Key, this.Description);
}
}
接下来,从字典中投射Job
列表,如下所示:
var jobList = this.jobs
.Select(it =>
new Job
{
Key = it.Key,
Description = it.Value
})
.ToList();
不是在for-each循环中添加字典项,而是按如下方式绑定ListBox
的数据源:
this.listBox1.DataSource = jobList;
关于它。列表框将通过调用ToString()
类中重写的Job
方法来显示每个项目。
现在您可以通过转换SelectedItem
/ SelectedItems
来访问作业对象及其键,如下所示:
var job = this.listBox1.SelectedItem as Job;
// job.Key