2016-02-26 90 views
0

我已經(保存在var中count)的ids已知數量的,我希望得到一個進程內循環時,每個ID具有OCCURENCES數量:如何在循環內發生id時在hashmap中增加值?

//init hashtable 
Hashtable hashtable = new Hashtable(); 
for (int i=0; i<count;i++) 
{ 
    hashtable.Add(i, 0); 
} 

for (int i=0; i<count;i++) 
{ 
    //some process to get and id 
    // for instance 
    // 14 
    // 17 
    // 17 
    // 3 
    // how to search i id and increment value? 
} 

那麼結果將是

Hash(14,1) 
Hash(17,2) 
Hash(3,1) 

如何搜索和更新散列表值?

回答

1

這將得到值並使用item indexer將其設置爲新值。 HashTable類不是強類型的,所以你必須將它明確地轉換回int類型。

for (int i=0; i<count;i++) 
{ 
    var id = ...get id...; 
    hashtable[id] = ((int)hashtable[id]) + 1; 
} 
1

我建議使用Dictionary<int,int>而不是每個字典輸入鍵映射到值的出現次數。

var idMap = new Dictionary<int,int>(); 
for (int i=0; i<count;i++) 
{ 
    if(idMap.ContainsKey(id)) 
    { 
    idMap[id] = idMap[id]+1; 
    } 
    else 
    { 
    idMap[i] = 1; 
    } 
} 
+0

我在這裏尋找效率就像10億條記錄一樣,將字典的行爲比hashmap更好嗎? – cMinor

+1

無論哪種方式都不適合內存 - 那麼您需要一種不同的方式來解決您的問題。 – BrokenGlass

+0

好的,在速度方面?你還會建議使用Dictionary嗎? – cMinor