Click here to Skip to main content
15,922,894 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a dictionary
Dim Dic as dictionary(integer, integer) 
123, 3
345, 21
22, 0
56, 1

I sorted Dic by values
Dim DicSort As List(Of KeyValuePair(Of integer, Integer)) = Dic.ToList 

DicSort.Sort(Function(x, y) y.Value.CompareTo(x.Value))
22, 0
25, 1
123, 3
345, 21

I want remove Dic values and put index number (or current count of Dic at runtime)
Like as this,
22, 0
25, 1
123, 2
345, 3

What I have tried:

Dim OrderDic = Dic.ToDictionary(Function(x) x.Key, Function(y)  Dic.Values.Count)

But i have this result,
22, 4
25, 4
123, 4
345, 4
Posted
Updated 25-Jun-18 2:10am
v2
Comments
Richard MacCutchan 25-Jun-18 6:37am    
Dic.Values.Count is a constant number, and will always be 4 in this case. You need some item that gives the position in the dictionary.

1 solution

Check this:
VB.NET
Dim oDict As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)
oDict.Add(123, 3)
oDict.Add(345, 21)
oDict.Add(22, 0)
oDict.Add(56, 1)


'sort by key and
'replace values with index of sorted element
oDict = oDict _
	.OrderBy(Function(x) x.Key)	_
	.Select(Function(x, i) New KeyValuePair(Of Integer, Integer)(x.Key, i)) _
	.ToDictionary(Function(kvp) kvp.Key, Function(kvp) kvp.Value) 


Good luck!
 
Share this answer
 
v2
Comments
gacar 25-Jun-18 9:13am    
Thank you very much Maciej Los, worked.
Maciej Los 25-Jun-18 9:23am    
Great! You're very welcome.
Richard Deeming 26-Jun-18 12:01pm    
You don't need that .ToList() call in there. :)
Maciej Los 26-Jun-18 13:37pm    
Good point!
Updated!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900