如何从Linq到SQL查询返回名称/值对列表?

时间:2012-09-12 18:24:06

标签: .net linq-to-sql

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

2 个答案:

答案 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之前,这不会运行查询。