1

我正在寻找一种直接从 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
4

2 回答 2

2

你可以使用ToDictionary

可能看起来像这样

Dim dict As Dictionary(Of String, Interger) = users .ToDictionary(Function(u) u.CommonName,Function(u) u.CreatedTransactions.Count )
于 2012-09-12T18:28:52.933 回答
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在第一次枚举之前,这不会运行查询。

于 2012-09-12T18:31:58.527 回答