开发者

LINQ. Reducing the code by using dynamic queries

开发者 https://www.devze.com 2023-03-17 11:11 出处:网络
I use the following code to fill the Table1 dictionary with the information found within the LINQ query.

I use the following code to fill the Table1 dictionary with the information found within the LINQ query.

 Dim DB As New DatabaseDataContext
 Dim Table1 As New Dictionary(Of String, Integer)
 Dim Table2 As New Dictionary(Of String, Integer)

        Private Function FillTable() As Dictionary(Of String, Integer)
            Table1.Clear()
            Dim Query = From c In DB.Table1 Select New With _
                                     {.Table1ID = c.Table1ID, .Table1 = c.Table1}
            For Each c In Query
                Table1.Add(c.Table1, c.Table1ID)
            Next
            Return Table1
        End Function

What changes should i make to the function above to fill any given TableXXX dictionary? You see, I would not like to use the function below to fill the Table2 dictionary.

        Private Function FillTable2() As Dictionary(Of Str开发者_如何学运维ing, Integer)
            Table2.Clear()
            Dim Query = From c In DB.Table2 Select New With _
                                     {.Table2ID = c.Table2ID, .Table2 = c.Table2}
            For Each c In Query
                Table2.Add(c.Table2, c.Table2ID)
            Next
            Return Table2
        End Function


What about the "ToDictionary()" extension method?

http://msdn.microsoft.com/en-us/library/bb549277.aspx


I don't know if this is true but this seems the VB version of the MS c# SimpleLinqToDatabase sample app.

If that is so it would work if you make all your Table row data model types have the same properties TableID and table. Then getting the table data with the generic method. If you don't want that you will need to alter the base model to have a property accessor by string with reflection, but that is not very clever and fast to do on the datamodel.

    Private Function FillTable(Of T)() As Dictionary(Of String, Integer)
        Dim dict as New Dictionary(Of String, Integer)
        Dim Query = From c In DB.GetTable(Of T) Select New With _
                                 {.TableID = c.TableID, .Table = c.Table}
        For Each c In Query
            dict.Add(c.Table, c.TableID)
        Next
        Return dict
    End Function

Then call this with:

Dim result as Dictionary(Of String, Integer)
result = FillTable(Of Table1)()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号