[英]How to get the relative position of a Dictionary element?
我有下一個C#代碼:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("a", 3);
d.Add("b", 1);
d.Add("c", 0);
d.Add("d", -1);
d.Add("e", -9);
當搜索鍵“c”時,我想獲得該鍵的位置,即2.如果我查找鍵“e”,我想得到4.如果找不到該元素,則相對位置可以是-1。
補充:除非你有更好的想法,否則我想填充一個矩陣,其中包含由找到的字典元素的相對位置指示的行號中的某些值。 這同樣適用於列但使用不同的字典。 一個例子:
n4 n2 n1 n3 n9 . . .
a 4/4
b 2 8
c
d 8/2
e 4/3
.
.
.
其中a,b,c,d,e,...是字典“d”的鍵,n4,n2,n3,n9是第二字典的鍵。
我怎么能得到這個?
Dictionary<,>
沒有“位置”這樣的東西 - 它是一個無序的集合。
按鍵排序的類似集合 - SortedList<,>
和SortedDictionary<,>
。 請注意,這些是按鍵排序而不是插入時間。 目前尚不清楚你想要什么。
這應該做的伎倆:
d.Keys.ToList().IndexOf("c");
請注意,字典提供的O(1)時間查找在轉換為List時會丟失,因為列表本質上是O(n)。 因此,如果您的詞典中包含大量元素,那么最好使用另一個詞典或矩陣維度來存儲位置,因為以這種方式檢索它們可能會更慢。 事實上,您應該假設上面的單行類似於:
GetDictKeyPos(d, "c");
public int GetDictKeyPos(Dictionary<string, int> d, string key)
{
for (int i = 0; i < d.Count; ++i)
{
if (d.ElementAt(i).Key == key)
return i;
}
return -1;
}
作為旁注 ,如果你想要獲得該位置,你可能會假設該位置被保留。 微軟表示不要指望它,但在實踐中你會發現你可能依賴它。 (我從來沒有看到過被保留的位置。)話雖如此,直到微軟承認,“是的,是的,我們一直堅持你:位置實際上保存在字典中。我們只是不想承認它,因為我們希望能夠改變它,如果我們找到了更好的實現,但現在我們知道我們將離開它,所以在這里,你去......“,你可能不應該假設這個位置被保留。
最后,如果您計划抓住機會並假設它已被保留,並且您還計划使用上述方法獲取位置,那么請考慮將密鑰存儲在List中,因為查找時間將相同,並且List保證訂單得以保留。
字典沒有隱含的鍵值對順序。 如果你需要“位置”,你使用的方式是錯誤的。
編輯時:如果要實現矩陣,最好的辦法是使用多維數組。 例如:
int[,] matrix = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
相當於一個矩陣:
1 2
3 4
5 6
您可以使用matrix[i][j]
訪問其元素; 例如, matrix[0][0]
為1, matrix[0][1]
為2,等等。
您將無法使用任何內置集合數據結構,包括KeyedCollection
。 但是,您可以通過從Collection
派生並在內部包含一個Dictionary
來快速查找鍵來輕松創建自己的集合類。 Collection
類本身提供了索引檢索的功能。
public class KeyValueCollection<TKey, TValue> : Collection<KeyValuePair<TKey, TValue>>
{
private Dictionary<TKey, TValue> m_Dictionary = new Dictionary<TKey, TValue>();
public TValue GetValue(TKey key)
{
return m_Dictionary[key];
}
public void Add(TKey key, TValue value)
{
m_Dictionary.Add(key, value);
base.Add(new KeyValuePair<TKey, TValue>(key, value));
}
protected override void ClearItems()
{
m_Dictionary.Clear();
base.ClearItems();
}
protected override void InsertItem(int index, KeyValuePair<TKey, TValue> item)
{
m_Dictionary.Add(item.Key, item.Value);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
m_Dictionary.Remove(this[index].Key);
base.RemoveItem(index);
}
protected override void SetItem(int index, KeyValuePair<TKey, TValue> item)
{
m_Dictionary[this[index].Key] = item.Value;
base.SetItem(index, item);
}
}
如果您真的在尋找這種功能,為什么不維護一個輔助數據結構來維護添加元素的順序
(要么)
可能你只想維護一個存儲的結構列表
[{"a",-1},{"b",1},{"c",0},{"d",-1},{"e",-9}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.