2015-11-30 56 views
1

如何确定SortedList中最大的密钥是什么?我试过使用SortList.Max方法,我无法让它工作。获取SortList中的最大密钥

这里的示例代码:

Dim MySortedList As New SortedList(Of Int16, String) 

MySortedList.Add(1, "Item 1") 
MySortedList.Add(2, "Item 2") 
MySortedList.Add(3, "Item 3") 
MySortedList.Add(4, "Item 4") 

'I added this just to demonstrates the sorted list is working 
Response.Write(MySortedList(4)) 

'Now... how to I get the max 'Key' from the sorted list? 
'In this example I want it to return the number '4'. 

Dim MyMaxKey = MySortedList.Max <---- This doesn't work. Added as an example. 

Response.Write(MyMaxKey) 

回答

1

你可以这样说:

Dim MyMaxKey = MySortedList.Keys.Max() 
+0

优秀。这也适用。快速的问题,如果你不介意......你会如何使用它作为“MySortedList.Max”?我找不到一个例子。我假设你可以,因为它被列为(我将调用)SortedList对象的“直接”方法。 – ptownbro

+0

'Max'是为IEnumerable(Of T)'接口定义的扩展方法。在这种情况下,T是一个KeyValuePair(Of Int16,String)'。在一系列KeyValuePair(s)上调用Max方法没有任何意义。你将如何计算哪个KeyValuePair更大? –

+0

了解。谢谢 – ptownbro

2

由于SortedList的排序由键,就可以简单地采取的最后一个项目的关键 - 这是最大关键:

Dim MyMaxKey = MySortedList.Last().Key 

https://dotnetfiddle.net/l1d3AF

+0

啊。谢谢。这样可行。 – ptownbro