从IEnumerable对象向ComboBox添加项目 [英] Add Items to ComboBox from an IEnumerable object
问题描述
我有一个 System.Timers.Timer
,它每5秒更新一次我的获胜表单应用程序组件。
I have a System.Timers.Timer
that updates my win form application components in every 5 seconds.
我有一个comboBox和全局 IEnumerable< Person>
列表,该列表也每5秒更新一次。
我需要在组合框中添加人员名称。如果名称已经在列表中,我就不应该添加。
I have a comboBox and global IEnumerable<Person>
list that updated also in everty 5 seconds.
I need to add persons name to combobox. If the name is already in the list, i should not add.
如何进行?
这是计时器事件中的代码。这增加了很多次,我不确定使用 foreach来做到这一点,
也许 IEnumareble
接口有一个更简单的方法。 / p>
How can I proceed?
Here is the code inside the timer event. This adds multiple times and i am not sure to do that with foreach,
maybe IEnumareble
interface has an easier way.
foreach (Persons person in personsList)
{
comboBox.Items.Add(person.Name);
}
推荐答案
这是更简单的方法之一假设您使用的是.NET 3.5或更高版本,则可以解决此问题:
This is one of the simpler solutions to this problem, assuming you're using .NET 3.5 or greater:
foreach(Person person in personsList)
{
if(!comboBox.Items.Cast<string>().Contains(person.Name))
{
comboBox.Items.Add(person.Name);
}
}
如果您使用的是3.0或更早版本,则
If you're using 3.0 or earlier, you'll have to do the search yourself:
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);
}
这篇关于从IEnumerable对象向ComboBox添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!