アイテムがリストビューに追加されたときにリストビューの冗長性を回避する方法は何ですか..imusingwinforms c#.net ..つまり、listview1のアイテムとlistview2のアイテムを比較して、あるリストビューから別のリストビューに、ターゲットリストビューにすでに入力されているアイテムを入力できませんでした。あるリストビューから別のリストビューにアイテムを追加することはできませんが、重複アイテムを追加しています。 ?
4629 次
3 に答える
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);
}
c#netのボタンクリックで選択したアイテムをあるリストビューから別のリストビューにコピーする方法でも同様の問題を参照できますか?
于 2010-03-09T11:37:18.207 に答える
0
提案されているように、ハッシュテーブルはそのような冗長性を阻止するための良い方法です。
于 2010-03-09T06:57:12.093 に答える
0
ディクショナリー...任意の配列..すべての可能なリスト。アイテム/サブアイテムをループスローし、それらを「配列」に追加してから、配列をループスローして他のリストと照合します。
これは、ボタンクリックで重複を削除するために使用する例ですが、ニーズに合わせてコードに簡単に変更できます。
以下を使用して、ボタンクリックでリストビューの「重複」を削除しました。自分で使用するためにコードを編集できるサブアイテムを検索しています...
辞書と私が書いた少し簡単な「更新」クラスを使用します。
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
}
幸運を!
于 2011-08-24T13:03:36.720 に答える