.NET ForEachだけではない繰り返しメソッド

こんな使い方ができるとは知りませんでした。


@IT KeyValuePair(Of Integer, String)のコレクションよりValueに一致する最初のKeyを取得したい

ForEachだけではない繰り返しメソッド

長いジェネリック・クラスの名前を短く記述するには?[2.0のみ、C#、VB]


Imports IntStrItem = _

      System.Collections.Generic.KeyValuePair(Of Integer, String)


 

Imports IntStrList = _

  System.Collections.Generic.List(Of _

    System.Collections.Generic.KeyValuePair(Of Integer, String))


 


 

Module Module1


 

    Sub Main()

        Dim List As New System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of Integer, String))

        List.Add(New System.Collections.Generic.KeyValuePair(Of Integer, String)(1, "りんご"))

        List.Add(New System.Collections.Generic.KeyValuePair(Of Integer, String)(2, "みかん"))

        List.Add(New System.Collections.Generic.KeyValuePair(Of Integer, String)(3, "すいか"))

        List.Add(New System.Collections.Generic.KeyValuePair(Of Integer, String)(4, "みかん"))


 

        '方法その1

        Dim orange As System.Collections.Generic.KeyValuePair(Of Integer, String) = _

        List.Find(AddressOf IsOrange)

        Console.WriteLine("Key:{0} Value{1}", Orange.Key, Orange.Value)


 

        '方法その2_1(コンストラクタでフィルタ値を指定)

        Dim filter As IntStrItemFilter(Of Integer, String) = New IntStrItemFilter(Of Integer, String)("りんご")

        Dim apple As IntStrItem = List.Find(AddressOf filter.IsMatch)

        Console.WriteLine("Key:{0} Value{1}", apple.Key, apple.Value)


 

        '方法その2_2(プロパティでフィルタ値を指定)

        filter.FilterValue = "すいか"

        Dim watermelon As IntStrItem = List.Find(AddressOf filter.IsMatch)

        Console.WriteLine("Key:{0} Value{1}", watermelon.Key, watermelon.Value)


 

    End Sub


 

    Private Function IsOrange(ByVal item As System.Collections.Generic.KeyValuePair(Of Integer, String)) As Boolean

        Return (item.Value = "みかん")

    End Function


 


 

    Public Class IntStrItemFilter(Of TKey, TValue)


 

        Private _FilterValue As TValue


 

        Public Sub New(ByVal filterValue As TValue)

            _FilterValue = filterValue

        End Sub


 

        Public Property FilterValue() As TValue

            Get

                Return _FilterValue

            End Get

            Set(ByVal value As TValue)

                _FilterValue = value

            End Set

        End Property


 

        Public Function IsMatch(ByVal item As IntStrItem) As Boolean

            If (_FilterValue Is Nothing) Then Return False

            Return (_FilterValue.Equals(item.Value))

        End Function


 

    End Class


 

End Module