简体   繁体   English

如何从列表添加项目 <T> 进入组合框,但在C#中不重复

[英]How to add items from List<T> into Combo Box but not duplicates in C#

In a WPF project I have a simple List called "items" containing the following: 在WPF项目中,我有一个名为“ items”的简单列表,其中包含以下内容:

EURUSD
EURUSD
NZDUSD

I want to populate a comboBox with unique instances of the above. 我想用上面的唯一实例填充comboBox。 So I wrote a foreach loop to go through the "items" members, and then a for loop to check whether a given member was already present within the combobox (so not to add duplicates). 因此,我编写了一个foreach循环来遍历“ items”成员,然后编写一个for循环来检查组合框中是否已经存在给定成员(以便不添加重复项)。 My code is: 我的代码是:

private void Test(object sender, EventArgs e)
{
    comboBox.Items.Clear();
    foreach (var positionz in items)
    {

        if (items.Count == 0) return;
        int combocount = comboBox.Items.Count;
        if (combocount == 0)
        {
            comboBox.Items.Add(positionz.Symbol);
            continue;
        }
        for (int i = 0; i < combocount; i++)
        {

            if (comboBox.Items[i].ToString() == positionz.Symbol)
            {
               label.Content=i + "Good "  + positionz.Symbol + " matches combo item " + comboBox.Items[i].ToString();
                continue;
            }
            else { comboBox.Items.Add(positionz.Symbol); }
            label_Copy.Content = i;
        }

    }
}

The label stuff is just me trying to catch at what point the mistake is. 标签的东西只是我试图抓住错误的原因。 For same reason when it matches the duplicate and continues to the next "i", it still adds the symbol to the combobox. 出于相同的原因,当它与重复项匹配并继续到下一个“ i”时,仍会将符号添加到组合框。

I'm sure I'm overlooking something silly but I can't figure it out. 我确定我忽略了一些愚蠢的事情,但我无法弄清楚。

Leaving aside data binding and possible equality issues... using System.Linq; 抛开数据绑定和可能存在的平等问题... using System.Linq; you could replace the complete foreach with just: 您可以将完整的foreach替换为:

foreach (var symbol in items.Select(i => i.Symbol).Distinct())
{
    combobox.Items.Add(symbol);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM