首页 文章

如何根据另一个listBox的索引填充listBox

提问于
浏览
0

好 . 所以我创建了一个字典,将演员(在13,559行txt文件中)分配给他们的电影(在同一个txt文件中) . 例如,演员1被分配给电影“a”,“b”和“c”,演员2被分配给电影“d”和“e” . 在我的字典中,键是字符串值(actor),电影存储在List中并分配给键 .

我已经附加了我正在使用的GUI,但其中的一点是,当listBox1中的用户选择Actor A时,我希望Actor A的电影出现在listBox2中 . 当然,如果选择了Actor B,我希望他的电影能够显示在listBox 2和Actor A的电影中去除 . 换句话说,我希望listBox2在滚动listBox1时不断更新 .

如果您有任何建议,请分享!谢谢!

// dictionary already full of actors and movies
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // as index of listBox1 changes, what should I do in this method?
}

enter image description here

1 回答

  • 1

    尝试这样的事情:

    using System.Linq
    
    ...
    
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // filter movies according to selected value in first listbox
        var movies = myDic.Where(x => x.Key == listBox1.SelectedItem.ToString()).SelectMany(x => x.Value).ToList();
        listBox2.Items.Clear();
        foreach (string movie in movies)
        {
            listBox2.Items.Add(movie);
        }
    }
    

    根据您填写 listBox1 的方式,您可能需要使用 listBox1.SelectedValue 而不是 listBox1.SelectedItem.ToString()

相关问题