|
Imports System.Linq.Expressions Imports System.Linq Imports System.Collections.Generic Class A Public Property Name As String Public Property ID As Integer Public Overrides Function ToString() As String Return ID & "," & Name End Function End Class Module Module1 Function MyWhere(Of T)(ByVal data As IEnumerable(Of T), ByVal propname As String, ByVal value As Object) As IEnumerable(Of T) Dim param = Expression.Parameter(GetType(T), "x") Dim body = Expression.Equal(Expression.MakeMemberAccess(param, GetType(T).GetProperty(propname)), Expression.Constant(value)) Dim lambdaexpr As Object = Expression.Lambda(body, param).Compile() Return data.Where(CType(lambdaexpr, Func(Of T, Boolean))) End Function Sub Main() Dim list As New List(Of A) list.Add(New A() With {.ID = 1, .Name = "a"}) list.Add(New A() With {.ID = 2, .Name = "b"}) list.Add(New A() With {.ID = 3, .Name = "c"}) Console.WriteLine(MyWhere(list, "Name", "a").First()) Console.WriteLine(MyWhere(list, "ID", 2).First()) End Sub End Module '''如果是linq to sql/ef,可以用下面的: Imports System.Linq.Expressions Imports System.Linq Imports System.Collections.Generic Class A Public Property Name As String Public Property ID As Integer Public Overrides Function ToString() As String Return ID & "," & Name End Function End Class Module Module1 Function MyWhere(Of T)(ByVal data As IQueryable(Of T), ByVal propname As String, ByVal value As Object) As IQueryable(Of T) Dim param = Expression.Parameter(GetType(T), "x") Dim body = Expression.Equal(Expression.MakeMemberAccess(param, GetType(T).GetProperty(propname)), Expression.Constant(value)) Dim lambdaexpr As Object = Expression.Lambda(body, param) Return data.Where(CType(lambdaexpr, Expression(Of Func(Of T, Boolean)))) End Function Sub Main() Dim list As New List(Of A) list.Add(New A() With {.ID = 1, .Name = "a"}) list.Add(New A() With {.ID = 2, .Name = "b"}) list.Add(New A() With {.ID = 3, .Name = "c"}) Console.WriteLine(MyWhere(list.AsQueryable(), "Name", "a").First()) Console.WriteLine(MyWhere(list.AsQueryable(), "ID", 2).First()) End Sub End Module |
|
|