从C#中的ListBox中删除重复的项目

时间:2014-10-20 17:36:04

标签: c# winforms listbox duplicates listboxitem

我有一个ListBox,有10个这样的项目:

1:3
2:2
2:2
2:2
1:3
6:8
6:8
9:1
7:2
9:1

我想删除重复项,因此结果如下所示:

1:3
2:2
6:8
9:1
7:2

以下是我的尝试:

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)
}

2 个答案:

答案 0 :(得分:1)

        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();

这是最简单的方法。而不是直接listBox.Items.Add(value)添加List<string>中的值并将其添加为listBox的DataSource。在放置Distinct()之前,您将执行DataSource操作。如果这是asp.net,那么你需要listBox.DataBind()

修改

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 !
}

答案 1 :(得分:0)

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);
    }
}