2014-10-20 70 views
0

我有一個ListBox有10個項目是這樣的:刪除在C#中從一個ListBox重複項目

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

回答

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。在放入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 ! 
} 
+0

我怎麼能幹淨列表框的項目? listBox2.Items.Clear();不工作:( – Shadan64 2014-10-20 18:26:37

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