[英]Which collection type should I use?
我有三個ListBox:lb1,lb2和lb3。
讓我們說在lb1中有4個元素,在lb2中是5個元素。
(lb1和lb2)的每個唯一組合可以分配給lb3中的元素。
我希望將這些組合和關聯存儲在一個集合中。 我的第一個是使用KeyValuePair,Key =(lb1Element1_lb2Element1),Value = lb3Element1。
但是通過這個解決方案,我會遇到問題。 假設我刪除lb1Element1,沒有選項(?)刪除KeyValuePair-List中出現lb1Element1的所有其他組合。
在這種情況下哪種收集類型最好?
在此先感謝約翰
編輯:所有3個列表框都包含數字。
您可以使用Dictionary<string,string>
作為keyvalue,它還提供Remove()
Dictionary<string, string> items = new Dictionary<string, string>();
items.Remove("mykey");
2個字典怎么樣,1個用於lb1,1個用於lb2:
Dictionary<string, Dictionary<string,string>>
第一個詞:關鍵是每個lb1值,值是lb2的所有值(詞典中鍵和值相同)第二個詞:鍵是每個lb2值,值是lb1的所有值
如果從lb2列表框中刪除選項“x”,然后找到已刪除的lb2值的所有連接的lb1值,則從第1個刪除所有具有“x”作為lb2值的對,然后刪除整個“x” “第二個關鍵詞:
Foreach(var lb1value in Dic2.ElementAt("x").value.keys)
{
Dic1.ElementAt("lb1value").
value.RemoveAt("x");
}
dic2.removeAt("x");
為什么不為密鑰創建類:
public class YourKey
{
public int Item1 { get; private set; }
public int Item2 { get; private set; }
public YourKey(int item1, int item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override bool Equals(object obj)
{
YourKey temp = obj as YourKey;
if (temp !=null)
{
return temp.Item1 == this.Item1 && temp.Item2 == this.Item2;
}
return false;
}
public override int GetHashCode()
{
int hash = 37;
hash = hash * 31 + Item1;
hash = hash * 31 + Item2;
return hash;
}
}
然后,您可以在Dictionary<YourKey, int>
來存儲所有值。
這樣做的好處是只能存儲Item1和Item2的每個組合的一個值。
如果要刪除數字中包含項目1 == 1的所有條目:
var entriesToDelete = yourDictionary.Where(kvp => kvp.Key.Item1 == 1).ToList();
foreach (KeyValuePair<YourKey, int> item in entriesToDelete)
{
yourDictionary.Remove(item.Key);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.