LINQ。使用动态查询减少代码
我使用以下代码使用 LINQ 查询中找到的信息填充 Table1 字典。
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
我应该对上面的函数进行哪些更改才能填充任何给定的 TableXXX 字典? 你看,我不想使用下面的函数来填充 Table2 字典。
Private Function FillTable2() As Dictionary(Of String, 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
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 String, 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“ToDictionary()”扩展方法怎么样?
http://msdn.microsoft.com/en-us/library/bb549277.aspx
What about the "ToDictionary()" extension method?
http://msdn.microsoft.com/en-us/library/bb549277.aspx
我不知道这是否属实,但这似乎是 MS c# SimpleLinqToDatabase 示例应用程序的 VB 版本。
如果是这样的话,如果您使所有表行数据模型类型具有相同的属性 TableID 和 table,那么它将起作用。然后用通用方法获取表数据。如果您不希望这样做,则需要更改基本模型,以通过带有反射的字符串来获取属性访问器,但这在数据模型上并不是非常聪明和快速。
然后用以下命令调用它:
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.
Then call this with: