2017-02-21 3 views
0

いくつかのプロパティのうちの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 
+0

別のキーのために、異なる機能を持つ単一の関数から辞書を返すことができます。 – Lali

+0

あなたは正しいですが、この関数の目的は単一のプロパティに対して1つのカウントを返すことだけです。私はどちらかのプロパティに基づいて一度に1つのカウントを取得する必要があります。コレクション内の特定のオブジェクトの任意のプロパティからカウントを得ることができる単一の関数を記述するためのパターンがあるかどうかは不思議でした。 – Geekn

+0

その後、そのプロパティも渡す必要があります。現在、関数は既にプロパティーをチェックすることを知っているので、値だけを渡しています – Lali

答えて

1

方法があるはずのように感じています。 ただし、代わりに一般的にする方がよいでしょう。型はIComparable型である必要がありますので、ターゲット値との等価性をチェックできます。

Public Function GetCountBy(Of T As IComparable)(selector As Func(Of Student, T), value As T) As Integer 
    Return _students.Where(Function(s) selector(s).CompareTo(value) = 0).Count() 
End Function 

Console.WriteLine(GetCountBy(Function(s) s.ID, 1)) 
Console.WriteLine(GetCountBy(Function(s) s.Name, "Stephen")) 

p.s. ToListメソッドへのあなたの呼び出しは()

不要です。しかし、あなたが行ったら、これははるかにあなたにもちょうど

Public Function CountWhere(predicate As Func(Of Student, Boolean)) 
    Return _students.Where(predicate).Count() 
End Function 
Console.WriteLine(CountWhere(Function(s) s.ID = 1)) 

あなたはさらにこれを一般化することができ、完全な述語の代わりに、セレクタ機能と値を渡すかもしれませんだから、学生だけでなくコレクションにも適用してください。

Public Function CountWhere(Of T)(coll As IEnumerable(Of T), predicate As Func(Of T, Boolean)) 
    Return coll.Where(predicate).Count() 
End Function 
Console.WriteLine(CountWhere(_students, Function(s) s.ID = 1)) 
+0

これはまさに私が望んでいたものです。時間を割いていただきありがとうございます。 – Geekn

関連する問題