我使用以下代码用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
答案 0 :(得分:1)
我不知道这是否属实,但这似乎是MS c#SimpleLinqToDatabase示例应用程序的VB版本。
如果是这样,如果您使所有表行数据模型类型具有相同的属性TableID和表,它将起作用。然后使用泛型方法获取表数据。如果你不希望你需要改变基本模型以通过带反射的字符串来获得属性访问器,但这对于数据模型来说不是很聪明和快速。
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
然后用以下方式调用:
Dim result as Dictionary(Of String, Integer)
result = FillTable(Of Table1)()
答案 1 :(得分:1)
“ToDictionary()”扩展方法怎么样?