2012-05-08 55 views
0

我有一本按降序排列的字典。每個字符串(鍵)是一個術語,int(值)是它的數量。我如何得到第一個計數?因爲它指的是最大計數(頻率).......提前致謝。在字典中的第一個項目

Just to inform some of whom commented that the dictionary<string,int> will change its 
rank. Be sure, if you are grouping the dictionary by its count, there is no problem 
with the order . Always the dictionary will come with highest count at first. 
+1

'dict.First()'?! http://stackoverflow.com/a/436957/284240您可能想要使用['OrderedDictionary'](http://msdn.microsoft.com/zh-cn/library/system.collections.specialized.ordereddictionary.aspx )而不是 –

+0

字典是散列表。他們沒有排序。向我們展示一些代碼。 – Steven

+0

@Tim Schmelter你是說Dict.value ....對嗎? – FSm

回答

6

什麼意思是'字典按降序排序'? A Dictionary<TKey,TValue>顧名思義就是未分類!你的意思是SortedDictionary<TKey,TValue>?如果是這樣,你可以使用:

var firstCount = sortedDictionary.First().Value; 
+0

nope,它只是一個字典,但我摸索它的價值 – FSm

+0

SortedDictionary不支持按值降序或排序(我相信這是這種情況)。 –

+0

@Chris,它的確如此。我很確定。 – FSm

1

您不能依靠Dictionary保持有序(當然,除了它是OrderedDictionary)。如果您使用的是OrderedDictionary,你可以使用它的索引:

var maximumCount = myDictionary[0]; 

var maximumCount = myDictionary.First().Value; 

編輯:如果你想在整個辭典的最高數,你也可以只使用:

var maximumCount = myDictionary.Max(entry => entry.Value); 
+0

@ Botz中出現的次數最高,您說得對,但我已經將每個返回的dic的每個Maxcount放在數組[int]中。感謝您的通知。 – FSm

0

我相信你使用的是錯誤的字典類型。改爲使用OrderedDictionary<>。它將爲您提供有保證的訂單和索引器。

OrderedDictionary list = new OrderedDictionary(); 

// add a bunch of items 

int firstValue = (int)list[0]; 

與OrderedDictionary唯一的缺點是,它不是通用的,但這裏是你如何使它通用。 http://www.codeproject.com/Articles/18615/OrderedDictionary-T-A-generic-implementation-of-IO

+0

我認爲沒有錯。我的字典總是以最高的第一個 – FSm

+0

@Qaesar - 字典<>集合的順序不保證與您添加項目時的順序相同。這可能看起來像是因爲它現在正在工作,但在生產中它可能無法產生正確的結果。我希望你不要寫股票代碼或任何類型的金融產品。 –

+0

哈哈...不,它不是金融產品的類型。但相信我這不是問題,因爲我一次返回所有dic的價值。 – FSm