【问题标题】:Removing duplicate items from a ListBox in C#从 C# 中的 ListBox 中删除重复项
【发布时间】:2014-10-20 17:36:03
【问题描述】:

我有一个 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)
}

【问题讨论】:

    标签: c# winforms listbox duplicates listboxitem


    【解决方案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&lt;string&gt; 中的值并将其添加为列表框的DataSource。在放置DataSource 之前,您将执行Distinct() 操作。如果这是 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 !
    }
    

    【讨论】:

    • 如何清理列表框项目? listBox2.Items.Clear();不工作:(
    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多