我想运行一个查询来获取logType的不同“logName”项的字符串数组。以下工作很棒:
Dim stringArray() As String = (From item In dc.Vw_Logs
Where item.LogType = [Passed in logType]
Select item.LogName Distinct).ToArray()
但是,这仅在设置特定LogType时有效。我希望logType子句是可选的。为了尝试实现这一点,我重写了查询:
Dim q = From item In dc.Vw_Logs Distinct
If not logType is nothing Then
q = q.Where(Function(item) item.LogType = logType)
End If
q.Select(Function(item) item.LogName)
Dim stringArray() As String = q.ToArray()
有了这个,我收到以下错误:
Value of type '1-dimensional array of Vw_Log' cannot be converted
to '1-dimensional array of String'
绕过这个最好的方法是什么?我想避免迭代每个项目并进行投射。
感谢您的帮助
答案 0 :(得分:1)
错误是因为q不是字符串,而是dc.Vw_Logs中包含的类型。
我不再在VB中做太多编程了,但这应该让你接近。
Dim q = From item In dc
Where (logType Is Nothing Or item.LogType = logType)
Select item.LogName Distinct
logType Is Nothing Or item.LogType = logType
如果logType有值,您将获得匹配的项目;否则,你将获得所有物品。
答案 1 :(得分:1)
问题是这一行
q.Select(Function(item) item.LogName)
不会改变q,它只是丢弃select的结果,以便在你做
时Dim stringArray() As String = q.ToArray()
您正在尝试将原始q(类型为Vw_Log)转换为字符串数组。用这个替换最后两行:
Dim stringArray() As String = q.Select(Function(item) item.LogName).ToArray()
答案 2 :(得分:0)
不要重复使用q。第一个赋值是Vw_Log(),第二个赋值是String()。
您还可以合并最后两行以避免这种情况。