2010-03-09 43 views
1

什麼是避免冗餘列表視圖中的項目被添加到它.. 即時通訊使用winforms c#.net .. 我的意思是如何比較listview1中的項目和listview2中的項目,以便while添加項目從一個列表視圖到另一個它不能輸入已經進入目標列表視圖的項目.. 即時能夠添加項目從一個列表視圖到其他,但它是添加auplicate項目還有什麼辦法擺脫它..???如何使用散列表來避免項目添加到列表視圖時重複的項目?

回答

1

你能想到的東西,如:

Hashtable openWith = new Hashtable(); 
// Add some elements to the hash table. There are no 
// duplicate keys, but some of the values are duplicates. 
openWith.Add("txt", "notepad.exe"); 
openWith.Add("bmp", "paint.exe"); 
openWith.Add("dib", "paint.exe"); 
openWith.Add("rtf", "wordpad.exe"); 
// The Add method throws an exception if the new key is 
// already in the hash table. 
try 
{ 
    openWith.Add("txt", "winword.exe"); 
} 
catch 
{ 
    Console.WriteLine("An element with Key = \"txt\" already exists."); 
} 
// ContainsKey can be used to test keys before inserting 
// them. 
if (!openWith.ContainsKey("ht")) 
{ 
    openWith.Add("ht", "hypertrm.exe"); 
    Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); 
} 

我們滿足編輯後問題的變化,你可以做這樣的:

if(!ListView2.Items.Contains(myListItem)) 
{ 
    ListView2.Items.Add(myListItem); 
} 

你也可以參照類似的問題在How to copy the selected items from one listview to another on button click in c#net?

0

正如所建議的,散列表是一種很好的方法來阻止這種冗餘。

+0

我知道哈希表是解決方案,但即時通訊新它我不知道如何使用它?你能指導我嗎? – zoya 2010-03-09 07:01:57

+0

爲了清楚起見,我在一些示例中添加了另一個答案。 – Kangkan 2010-03-09 11:36:54

+0

感謝主席的幫助.. – zoya 2010-03-10 05:54:21

0

一個dictonary ...任何數組..所有可能的列表,只是循環拋出項目/子項目,將它們添加到「數組」然後循環拋出數組來檢查它öhrhr列表...

這裏是我用來刪除buttonclick上的dups的示例,但您可以輕鬆更改爲代碼以滿足您的需求。

我用下面的刪除「複本」,在點擊一個按鈕列表視圖,我正在尋找子項目,你可以爲自己使用編輯代碼...

使用字典和一點點簡單的「更新」類我寫了。

private void removeDupBtn_Click(object sender, EventArgs e) 
    { 

     Dictionary<string, string> dict = new Dictionary<string, string>(); 

     int num = 0; 
     while (num <= listView1.Items.Count) 
     { 
      if (num == listView1.Items.Count) 
      { 
       break; 
      } 

      if (dict.ContainsKey(listView1.Items[num].SubItems[1].Text).Equals(false)) 
      { 
       dict.Add(listView1.Items[num].SubItems[1].Text, ListView1.Items[num].SubItems[0].Text); 
      }  

      num++; 
     } 

     updateList(dict, listView1); 

    } 

,並使用小updateList()類...

private void updateList(Dictionary<string, string> dict, ListView list) 
    { 
     #region Sort 
     list.Items.Clear(); 

     string[] arrays = dict.Keys.ToArray(); 
     int num = 0; 
     while (num <= dict.Count) 
     { 
      if (num == dict.Count) 
      { 
       break; 
      } 

      ListViewItem lvi; 
      ListViewItem.ListViewSubItem lvsi; 

      lvi = new ListViewItem(); 
      lvi.Text = dict[arrays[num]].ToString(); 
      lvi.ImageIndex = 0; 
      lvi.Tag = dict[arrays[num]].ToString(); 

      lvsi = new ListViewItem.ListViewSubItem(); 
      lvsi.Text = arrays[num]; 
      lvi.SubItems.Add(lvsi); 

      list.Items.Add(lvi); 

      list.EndUpdate(); 

      num++; 
     } 
     #endregion 
    } 

祝你好運!

相關問題