以下代码从oracle数据读取器读取查询结果,并将每条记录存储在字典中,并将字典附加到数组列表中:
Dim dr As OracleDataReader = cmd.ExecuteReader()
'loop oracle data records and store them to dictionaries
'append dictionaries to an array list
Dim arr As New ArrayList
While dr.Read
Dim dict As New Dictionary(Of String, Object)
For count As Integer = 0 To (dr.FieldCount - 1)
dict.Add(dr.GetName(count), dr(count))
Next
arr.Add(dict)
End While
如何编写可用于从存储在数组列表中的字典中检索值的LINQ查询?请帮忙。我一直在寻找并没有得到任何好的答案
答案 0 :(得分:0)
首先,不要使用ArrayList
。它是为了向后兼容但没有用处。我可以简短回答 - LINQ与ArrayList
没有用。使用通用List(Of T)
和 LINQ 来搜索其中的值。也不需要Dictionary
。这是旧式的。我们使用Dictionary
,因为它有key
我知道,您尝试创建表结构但不需要这样做。首先,有System.Data.DataTable
,可以在客户端查询。
或者使用这种技术
Public Class User
Public Property Id As Integer
Public Property Name As String
Public Property Email As String
Public Property Country As String
End Class
Private Function LoadUsers() As List(Of User)
Dim uList As New List(Of User)()
' Some Code goes here
While dr.Read()
Dim u As New User()
u.Id = dr("Id")
u.Name = dr("Name")
u.Email = dr("Email")
u.Country = dr("Country")
uList.Add(u)
End While
. . . . . . .
Return uList
End While
' somewhere in class set member variable
_users = LoadUsers()
' And then you can search for info using LINQ
Public Function FindByCountry(ByVal country As String) As List(Of User)
Return _users.Where(Function(u) u.Country.Equals(country, StringComparison.OrdinalIgnoreCase))
End
这种方法的缺点 - 每个字段都需要Find
个函数。但是如果你可以自己传递一个函数呢?看 - 你有Name, email, Country
- 所有字符串。在这里你可以做什么
Class Client
Sub SearchStrings(ByVal searchOption String, Byval searchValue As String)
Dim f As Func(Of User, boolean)
If searchOption = "Name" Then
f = Function(u as User)(u.Name.Equals(searchValue , Stringcomparison.OrdinalIgnoreCase))
ElseIf searchOption = "Country" Then
f = Function(u as User)(u.Country.Equals(searchValue , Stringcomparison.OrdinalIgnoreCase))
ElseIf searchOption = "Email" Then
f = Function(u as User)(u.Email.Equals(searchValue , Stringcomparison.OrdinalIgnoreCase))
Else
. . . .
End If
dataGrd.DataSource = myRepository.FindByString(f)
End Sub
End Class
' In your repository class
public sub FindByString(ByVal f as Func(Of String, Boolean)) As List(Of User)
_users.Where(f).ToList()
End sub
' use this to search single user
public sub FindByInteger(ByVal f as Func(Of Integer, Boolean)) As User
_users.SingleOrDefault(f)
End sub
底线 - 放弃您的工作并使用现代高效的技术。以上只是他们中的几个