First item in a SortedDictionary?

前端 未结 2 692
梦谈多话
梦谈多话 2021-01-21 04:10

There are many, many threads on ways to get the \"first\" item from a Dictionary, and various answers as to why such a thing is not really a good idea beca

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 04:45

    Linq is mostly just a series of extension methods, so you can write own:

    Imports System
    Imports System.Collections.Generic
    Imports System.Runtime.CompilerServices
    
    Public Module EnumerableExtensions
    
         
        Public Function FirstValue(Of TKey, TValue)(source As SortedDictionary(Of TKey, TValue)) As TValue
            For Each kvp In source
                Return kvp.Value
            Next
            Return Nothing
        End Function
    
    End Module
    
    Public Module Module1
        Public Sub Main()
            Dim a As SortedDictionary(Of string, string) = new SortedDictionary(Of string, string)
            a.Add("foo", "1 - foo")
            a.Add("bar", "2 - bar")
            Console.WriteLine(a.FirstValue())
        End Sub
    End Module
    

    Here's the example running in dotnetfiddle.

提交回复
热议问题