单击列表对象并在另一个列表框C#中显示其他多个列表对象

时间:2012-04-05 01:42:48

标签: c# dictionary listbox datasource

我几乎要回答这个问题,但令人讨厌,并不完全。 到目前为止,我的代码是:

   private void lstIndividuals_SelectedIndexChanged(object sender, EventArgs e)
   {
        var individual = lstIndividuals.SelectedItem as Individual;
        var tempSimilarFilesToFile1 = new HashSet<Individual>();
        int Counter = 0;
        foreach (KeyValuePair<int, Individual> kvpInd in _Individuals1)
        {
            tempSimilarFilesToFile1 = new HashSet<Individual>();
            foreach (KeyValuePair<int, Individual> kvpInd2 in _Individuals2)
            {
                if (kvpInd.Value.name.name.ToLower() == kvpInd2.Value.name.name.ToLower())
                {
                    Counter++;
                    similarInds.Add(kvpInd.Value);
                    if (Counter >= 1)
                    {
                        tempSimilarFilesToFile1.Add(kvpInd2.Value);
                    }
                }
            }
        lstIndividuals2.DataSource = tempSimilarFilesToFile1.ToList();
        lstIndividuals2.DisplayMember = "DisplayName";
        lstIndividuals2.ValueMember = "id";
   }

正如您可能看到的那样,lstIndividuals2列表框项目正在快速缩放。我只想点击lstIndividuals

中的某个项目

然后我想要显示找到的类似记录(任何遵守规则的kvpInd.value.name.name == kvpInd2.value.name.name

所有类似的项目,我希望存储在tempSimilarFilesToFile1中,并且作为lstIndividual2的数据源

如果我解释得很糟,我道歉。

谢谢。

1 个答案:

答案 0 :(得分:0)

您每次都在外部循环中初始化tempSimilarFilesToFile1,因此您实际获得的列表包含_Individuals2中与_Individuals1中的最终项目相同的项目。只是尝试在外部循环中注释init语句,看看是否有帮助。

private void lstIndividuals_SelectedIndexChanged(object sender, EventArgs e)    
{
    var individual = lstIndividuals.SelectedItem as Individual;
    var tempSimilarFilesToFile1 = new HashSet<Individual>();
    int Counter = 0;
    foreach (KeyValuePair<int, Individual> kvpInd in _Individuals1)
    {
        // comment the statement below
        //tempSimilarFilesToFile1 = new HashSet<Individual>();
        foreach (KeyValuePair<int, Individual> kvpInd2 in _Individuals2)
        {
            if (kvpInd.Value.name.name.ToLower() == kvpInd2.Value.name.name.ToLower())
            {
                Counter++;
                similarInds.Add(kvpInd.Value);
                if (Counter >= 1)
                {
                    tempSimilarFilesToFile1.Add(kvpInd2.Value);
                }
            }
        }
    lstIndividuals2.DataSource = tempSimilarFilesToFile1.ToList();
    lstIndividuals2.DisplayMember = "DisplayName";
    lstIndividuals2.ValueMember = "id";
}