Combo boxes duplicate entries

前端 未结 4 1224
醉话见心
醉话见心 2021-01-07 01:27

I am adding items to combo box using comboBox.Items.Add(entry);. But how can I avoid duplicate entries (i.e same name entries) in combobox. Is there any lib fun

相关标签:
4条回答
  • 2021-01-07 01:33

    The Items collection has a Contains method

    if (!comboBox.Items.Contains(entry)) {
        comboBox.Items.Add(entry);
    }
    

    The ComboBox.Items property is of type System.Windows.Forms.ComboBox.ObjectCollection, which declares the Contains method like this

    public bool Contains(object value)
    

    If you want to use AddRange, you must provide the items in an array. Therefore you must make sure that this array does not contain duplicates. Moreover, if the ComboBox already contains items, you must make sure that this array does not contain the same items.

    Let's first assume that the ComboBox is empty and that your items are given by some enumeration (this could be a List<T> or an array for instance):

    comboBox.Items.AddRange(
        itemsToAdd
            .Distinct()
            .ToArray()
    );
    

    You must have a using System.Linq; at the top of your code. Also you might want to order the items. I assume that they are of string type:

    comboBox.Items.AddRange(
        itemsToAdd
            .Distinct()
            .OrderBy(s => s)
            .ToArray()
    );
    

    If the ComboBox already contains items, you will have to exclude them from the added items

    comboBox.Items.AddRange(
        itemsToAdd
            .Except(comboBox.Items.Cast<string>())
            .Distinct()
            .OrderBy(s => s)
            .ToArray()
    );
    

    (Again assuming that itemsToAdd is an enumeration of strings.)

    0 讨论(0)
  • 2021-01-07 01:35

    Use an HashSet class to bind the control, how depens from the presentation technology, or use the Distinct method of LINQ to filter duplicates.

    0 讨论(0)
  • 2021-01-07 01:36

    Check for the item before adding:

    if (!comboBox.Items.Contains(entry))
        comboBox.Items.Add(entry);
    
    0 讨论(0)
  • 2021-01-07 01:36

    How about Casting the items to String

    var check = comboBox1.Items.Cast<string>().Any(c => c.ToString() == "test");
    
    0 讨论(0)
提交回复
热议问题