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
Select all of the data in the required columns (including column headers) and select Data ribbon -> Remove duplicates.
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.
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]);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With