什麼是最好的方式來保持一個集合對象(例如List)在一個鍵/值的情況下,其中的關鍵是一個ID和值是一個類型T的集合?在鍵/值集合中使用列表<T>的最佳方式是什麼?
這是唯一的選擇,還是有更好的解決方案/在.NET 3.5中的這個另一個集合?
var x = new Dictionary<int, List<type>>();
什麼是最好的方式來保持一個集合對象(例如List)在一個鍵/值的情況下,其中的關鍵是一個ID和值是一個類型T的集合?在鍵/值集合中使用列表<T>的最佳方式是什麼?
這是唯一的選擇,還是有更好的解決方案/在.NET 3.5中的這個另一個集合?
var x = new Dictionary<int, List<type>>();
這是一個很好的解決方案,並且工作得很好 - 您正在有效地使用{key = int,value = 4 byte reference}的字典對象。
當您通過密鑰檢索值時,您將返回對堆上的List<T>
的引用,並且可以使用它。這對你的明顯問題將是一個非常有效和緊湊的解決方案。
我不知道這是你需要什麼,但我會砍它。
public Dictionary<int,List<T>> myFunction<T>()
{
var returnvalue = new Dictionary<int,List<T>>();
//Do some stuff with the collection.
return returnvalue;
}
,你可以調用
public void Main()
{
var functionreturn = myFunction<String>();
}
我不知道這是否會幫助你或沒有,但它可以幫助你改寫你的問題。
注意:以上是空碼,未經測試。
-1。更好地測試然後發佈,而不是快速提供。 – 2009-05-06 21:04:33
我不認爲框架內有任何東西,但我認爲PowerCollections庫中有一個MultiDictionary集合。你可以試試。
謝謝。我會看看。 – robertpnl 2009-01-06 13:58:03
我想你應該根據你的需要編寫你的包裝類。我的意思是,如果您需要存儲預製列表的字典,Dictionary<int, List<type>>
應該沒問題,只要它只是一個私人財產。你不應該公開暴露它,因爲它明顯暴露了太多的信息,並且由於缺乏協變性,你不能將它投射到IDictionary<int, IList<T>>
或類似的東西。
你最好的選擇是類似的東西:
class MyWrapper<T>()
{
private Dictionary<int, List<T>> dictionary { get; set; }
public MyWrapper() { dictionary = new Dictionary<int, List<T>>(); }
// Adds a new item to the collection
public void Add(int key, T item)
{
List<T> list = null;
if (!dictionary.TryGetValue(key, out list))
{
// If dictionary does not contain the key, we need to create a new list
list = new List<T>();
dictionary.Add(key, list);
}
list.Add(item);
}
public IEnumerable<T> this[int key]
{
get
{
List<T> list = null;
// We just return an empty list if the key is not found
if (!dictionary.TryGetValue(key, out list)) return new List<T>();
else return list;
}
}
}
顯然,您的需求可能會有所不同,你可能需要實現幾個接口等,但這是一般的想法。
如果你的ID是你的類型中的一員,你可能會考慮實施System.Collections.ObjectModel.KeyedCollection<TKey, TItem>
你正在尋找一個多值的字典,即一鍵集合,其中每個鍵可以有多個值? PowerCollections有這樣一個MultiDictionary。
您的意思是var x = new Dictionary>(); ? –
tuinstoel
2009-01-06 13:19:23
這個問題有點不清楚,請您重新解釋一下嗎?你問是否字典是一個很好的集合,用於保存鍵和值?代碼爲 – dalle 2009-01-06 13:21:01