Linq dynamic selection problem

I want to run a query to get a string array of various "logName" elements for logType. The following works great:

Dim stringArray() As String = (From item In dc.Vw_Logs 
    Where item.LogType = [Passed in logType] 
    Select item.LogName Distinct).ToArray()

      

However, this only works when a specific LogType is set. I would like the logType clause to be optional. To achieve this, I rewrote the query:

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()

      

With this, I get the following error:

Value of type '1-dimensional array of Vw_Log' cannot be converted 
to '1-dimensional array of String'

      

What's the best way to get around this? I would like to avoid repeating every element and casting.

Thanks for any help

0


a source to share


3 answers


The error is due to the fact that q is not a string, but a type contained in dc.Vw_Logs.

I don't program in VB anymore, but that should close you.



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

      

If logType is relevant, you will get items that match; otherwise, you will receive all items.

+1


a source


The problem is that this line

q.Select(Function(item) item.LogName)

      

doesn't change q, it just discards the selection result so that when you do



Dim stringArray() As String = q.ToArray()

      

You are trying to convert the original q (which is of type Vw_Log) to a string array. Replace the last two lines with the following:

Dim stringArray() As String = q.Select(Function(item) item.LogName).ToArray()

      

+1


a source


Do not reuse q. The first assignment is Vw_Log (), the second is String ().

You can also combine the last two lines to avoid this.

0


a source







All Articles