从IEnumerable对象向ComboBox添加项

时间:2011-03-15 17:10:22

标签: c# combobox

我有一个System.Timers.Timer,每隔5秒就会更新我的win表单应用程序组件。

我有一个comboBox和全局IEnumerable<Person>列表,它也在5秒内更新。 我需要将人名添加到组合框中。如果名称已经在列表中,我不应该添加。

我该怎么办? 这是timer事件中的代码。这会增加多次,我不确定foreach,可能会IEnumareble界面更简单。

foreach (Persons person in personsList)
{
  comboBox.Items.Add(person.Name);
}

5 个答案:

答案 0 :(得分:2)

这是解决此问题的最简单的解决方案之一,假设您使用的是.NET 3.5或更高版本:

foreach(Person person in personsList)
{
    if(!comboBox.Items.Cast<string>().Contains(person.Name)) 
    {
        comboBox.Items.Add(person.Name);
    }
}

如果您使用的是3.0或更早版本,则必须自己进行搜索:

foreach(Person person in personsList)
{
    bool contains = false;

    foreach(string item in comboBox.Items)
    {
        contains = string.Equals(item, person.Name);

        if(contains) break;
    }

    if(!contains) comboBox.Items.Add(person.Name);
}

答案 1 :(得分:2)

如果可能,使用DataBinding通常是好的。 WPF具有更好的绑定,允许MVVM。当您修改原始集合(实时)时,WPF实际上会进行修改,并且不必在每次传递时都读取所有内容。

每次通过读取所有项目都是一种糟糕的方法,但它很容易解决。最好是直接修改列表框,如果代码允许它(没有太多的更新,不是太时间关键)或者复制列表并只执行差异。 (通过1:删除组合框中新列表中不存在的任何项目。通过2:添加新列表中组合框中不存在的任何项目)

答案 2 :(得分:1)

一些方法可能是走动组合框中的所有项目,或者您可以跟踪已添加的名称列表。你有任何性能要求吗?

更简单的方法是直接绑定到人员列表并正确设置您的DisplayMember ......

答案 3 :(得分:1)

  

如果我绑定数据cmb.DataSource = personsList; cmb.DisplayMember =“主题”;这不会工作

它对我也没有用。经过一些尝试找到这个解决方案,也许它会帮助某人:

   IEnumerable<ICustomer> customers = GetCustomers(); //fill Ienumerable object list
   _comboBox.DataSource = customers.ToList(); //convert it to list and it binds fine
   _comboBox.DisplayMember = "Name";          // field Name from ICustomer
   _comboBox.ValueMember = "CustomerID";      // field CustomerID from ICustomer

答案 4 :(得分:1)

更简单的方法是:

comboBox.Items.Clear();
comboBox.Items.AddRange(personsList.Select(p => p.Name));

所有这一切都将清除comboBox并再次添加整个列表。或者,如果您不喜欢清除comboBox:

comboBox.Items.AddRange(personsList.Where(p => !comboBox.Items.Cast<string>().Contains(p.Name)).Select(p => p.Name));   

您不再需要foreach了。只需用这个替换你的所有代码!