在LinqToSql结果中通过MethodName(String)查找值?

时间:2015-01-16 07:23:32

标签: vb.net linq-to-sql

让我们说我的Person类看起来像这样:

Private Class Person
    Public Property Name As String
    Public Property Age As Integer
End Class

我有一个名为linqToSqlResult的结果,名字=" John"和年龄= 30岁。 现在我想得到这个人的姓名如下:

Dim name As String = CStr(GetValue(linqResult, "Name"))

我正在寻找这样的代码:

Private Function GetValue(ByRef linqToSqlResult As Object, fieldName As String) As Object
    'Here's the code I'm looking for??
End Function

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

由于缺乏信息,我假设传递的值LinqToSqlResultPerson类型查询的输出,如果不是,请更清楚地解释contents of LinqToSqlResult

你可以做的是以下(虽然不是最高效的代码):

Imports System.Reflection


Module Module1

    Sub Main()
        Dim i As Object = New Person With {.Name = "TestUser", .Age = 30}
        Console.WriteLine(GetValue(Of Person)(i, "Name").ToString())
        Console.WriteLine(Convert.ToInt32(GetValue(Of Person)(i, "Age").ToString()))
        Console.ReadLine()
    End Sub


    Private Function GetValue(Of T)(ByRef linqToSqlResult As Object, fieldName As String) As Object
        Dim myProp As PropertyInfo = GetType(T).GetProperties().Where(Function(x) x.Name.Equals(fieldName)).FirstOrDefault()
        If (myProp IsNot Nothing) Then
            Return myProp.GetValue(linqToSqlResult, Nothing)
        Else
            Throw New ArgumentException(" Some usefull message")
        End If
    End Function


End Module


Public Class Person
    Public Property Name As String
    Public Property Age As String
End Class

输出:

//TestUser
//30