Reputation: 3
I have a ListBox
with 10 items like this:
1:3
2:2
2:2
2:2
1:3
6:8
6:8
9:1
7:2
9:1
I want to remove duplicates so the result looks like this:
1:3
2:2
6:8
9:1
7:2
Here is what I have tried:
private void button2_Click(object sender, EventArgs e)
{
for (int p = 0; p < 10; p++)
{
a[p] = System.Convert.ToInt32(Interaction.InputBox("Please Enter 10 Number:", "", "", 350, 350));
listBox1.Items.Add(a[p]);
}
}
private void button3_Click(object sender, EventArgs e)
{
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 10; k++)
{
if (a[j] == a[k])
b = b + 1;
} //end of for (k)
listBox2.Items.Add(a[j] + ":" + b);
b = 0;
} //end og for (j)
}
Upvotes: 0
Views: 4525
Reputation: 94
private void button1_Click(object sender, EventArgs e)
{
string[] arr = new string[listBox1.Items.Count];
listBox1.Items.CopyTo(arr, 0);
var arr2 = arr.Distinct();
listBox1.Items.Clear();
foreach (string s in arr2)
{
listBox1.Items.Add(s);
}
}
Upvotes: 0
Reputation: 18127
List<string> p = new List<string>();
p.Add("1:2");
p.Add("1:4");
p.Add("1:3");
p.Add("1:2");
List<string> z = p.Distinct().ToList();
Here is the easiest way to do it. Instead of direct listBox.Items.Add(value)
add the values in List<string>
and add it as DataSource of the listBox. You will perform Distinct()
action before putting the DataSource
. If this is asp.net you need listBox.DataBind()
after that.
Edit:
private void button3_Click(object sender, EventArgs e)
{
List<string> list = new List<string>();
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 10; k++)
{
if (a[j] == a[k])
b = b + 1;
} //end of for (k)
list.Add(a[j] + ":" + b);
b = 0;
} //end og for (j)
List<string> result = list.Distinct().ToList();
listBox2.DataSource = result;
//listBox2.DataBind(); this is needed if it is asp.net, if it is winforms it is not needed !
}
Upvotes: 1