2010-03-09 41 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 
    } 

祝你好运!

相关问题