我正在寻找一种直接从Linq到SQL查询返回名称值对列表的方法,而不必像我在下面的代码中那样遍历结果:
Public Shared Function GetUserTransactionCounts(fromDate As DateTime, toDate As DateTime) As List(Of KeyValuePair(Of String, Integer))
Using dc As New ProntoDataContext()
Dim users As IEnumerable(Of User) = From u In dc.Users Where u.CreatedTransactions.Any(Function(t) t.TSCreate >= fromDate And t.TSCreate <= toDate)
Dim list As New List(Of KeyValuePair(Of String, Integer))
For Each user As User In users
Dim item As New KeyValuePair(Of String, Integer)(user.CommonName, user.CreatedTransactions.Count)
list.Add(item)
Next
Return list
End Using
End Function
答案 0 :(得分:2)
您可以使用ToDictionary
可能看起来像这样
Dim dict As Dictionary(Of String, Interger) = users .ToDictionary(Function(u) u.CommonName,Function(u) u.CreatedTransactions.Count )
答案 1 :(得分:2)
尝试转换为IEnumerable
,然后使用Select
:
Dim users As IEnumerable(Of User) = From u In dc.Users Where u.CreatedTransactions.Any(Function(t) t.TSCreate >= fromDate And t.TSCreate <= toDate)
Dim list As List(Of KeyValuePair(Of String, Integer)) = users.AsEnumerable().Select(Function(x) New KeyValuePair(Of String, Integer)(x.CommonName, x.CreatedTransactions.Count)).ToList()
编辑:如果您想制作IEnumerable
,请移除ToList
:
Dim enumerable As IEnumerable(Of KeyValuePair(Of String, Integer)) = users.AsEnumerable().Select(Function(x) New KeyValuePair(Of String, Integer)(x.CommonName, x.CreatedTransactions.Count))
在第一次枚举enumerable
之前,这不会运行查询。