いくつかのプロパティのうちの1つが特定の値を持つメンバのカウントを取得する同じ関数の2つのバージョンを記述していることがあります。私はfuncと他の例を見て、値がオブジェクトのいくつかのプロパティの1つと一致するカウントを行うための単一の関数を書くことができるかどうかを見てきました。あなたが右のラインに沿っているが、あなたのFuncがオブジェクトを返すために必要な...ラムダ式で使用されるラムダプロパティ値セレクタ
Module Test
Private _students As New List(Of Student)
Sub Main()
_students.Add(New Student(1, "Stephen"))
_students.Add(New Student(2, "Jenny"))
' I'd like to replace the following lines...
Console.WriteLine(GetCountByID(1))
Console.WriteLine(GetCountByName("Stephen"))
' with a single function that could be used like below.
'Console.WriteLine(GetCountByType(1, Student.ID))
'Console.WriteLine(GetCountByType("Stephen", Student.Name))
Console.ReadLine()
End Sub
Public Function GetCountByID(ByVal id As Integer) As Integer
Return _students.Where(Function(s) s.ID = id).ToList.Count
End Function
Public Function GetCountByName(ByVal name As String) As Integer
Return _students.Where(Function(s) s.Name = name).ToList.Count
End Function
' I know this is wrong below but I'm just writing it like I'm thinking about it in my head
'Public Function GetCountByType(ByVal value As Object, selectorProperty As Func(Of Student)) As Integer
' Return _students.Where(Function(s) s.selectorProperty = value).ToList.Count
'End Function
Public Class Student
Public Property ID As Integer
Public Property Name As String
Public Sub New(ByVal id As Integer, ByVal name As String)
Me.ID = id
Me.Name = name
End Sub
End Class
End Module
別のキーのために、異なる機能を持つ単一の関数から辞書を返すことができます。 – Lali
あなたは正しいですが、この関数の目的は単一のプロパティに対して1つのカウントを返すことだけです。私はどちらかのプロパティに基づいて一度に1つのカウントを取得する必要があります。コレクション内の特定のオブジェクトの任意のプロパティからカウントを得ることができる単一の関数を記述するためのパターンがあるかどうかは不思議でした。 – Geekn
その後、そのプロパティも渡す必要があります。現在、関数は既にプロパティーをチェックすることを知っているので、値だけを渡しています – Lali