Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in comboBox

Tags:

c#

I have to remove duplicates in a combobox.

private void cbnama_Click(object sender, EventArgs e)
{
    List<string>[] list;
    list = mDatabase.Viewpengujian();

    cbnama.Items.Clear();
    for (int i = 0; i < list[0].Count; i++)
    {
            cbnama.Items.Add(list[0][i]);
    }
}

Example:

test1
test2
test2
test3
test3
like image 866
bessie Avatar asked Mar 13 '12 10:03

bessie


People also ask

How do I remove duplicates in Merge?

Select all of the data in the required columns (including column headers) and select Data ribbon -> Remove duplicates.


3 Answers

Updated: Didn't notice you had a multidimensional list. @ntziolis is the first one to catch that and his answer is the right one.

If you're using C# 3.0 or later you could do:

list = list.SelectMany(i => i).Distinct().ToList();

Make sure you have using System.Linq on the top.

like image 136
gideon Avatar answered Oct 28 '22 19:10

gideon


u need to check item already added or not as below , shich skip the item which is already added in combo box

for (int i = 0; i < list[0].Count; i++)    
{                 

    if (!comboBox1.Items.Contains(list[0][i]) )
    {  
       cbnama.Items.Add(list[0][i]);     
     }
}
like image 28
Pranay Rana Avatar answered Oct 28 '22 21:10

Pranay Rana


In general this can be solved by using the Distinct extension method of the IEnumerable, see here:
http://msdn.microsoft.com/en-us/library/bb348436.aspx

But since you are using a multi dimensional list/array thing you need to SelectMany to flatten your dimensions before you can call Distinct, this also changes the rest of your code slightly so here is the hole method:

private void cbnama_Click(object sender, EventArgs e)
{
    // this will give you an IEnumerable<string>
    var list = mDatabase.Viewpengujian()
        .SelectMany(i => i)
        .Distinct();

    cbnama.Items.Clear();

    // since now list is a IEnumerable<string> you can just loop through it
    foreach (var item in list)
    {
        cbnama.Items.Add(item);
    }
}
like image 2
ntziolis Avatar answered Oct 28 '22 20:10

ntziolis