George H George H - 1 year ago 134 Question

LINQ with String.Join() error: "System.InvalidCastException: Unable to cast object of type '<DistinctIterator>

I'm trying to grab the distinct values of one column from a datatable using linq and use string.join to create a single string from the results but am getting:

"System.InvalidCastException: Unable to cast object of type 'd__7a`1[System.String]' to type 'System.String[]'."

My code is:

Dim retString As String = ""

Dim uniqueCC2 = (From d As DataRow In dt.AsEnumerable() _
Select d.Field(Of String)("CageCardID")).Distinct

'I get the error on the following line
retString = String.Join("</li><li>", uniqueCC2)
Catch ex As Exception
...error code...
End Try

Return "<li>" & retString & "</li>"

I have also tried this LINQ statement, but get the same error:

Dim uniqueCC2 = dt.AsEnumerable().Select(Function(s As DataRow) s.Field(Of String)("CageCardID")).Distinct()

The column in question (CageCardID) is varchar(8) a string.

When I dive into uniqueCC2 it shows the values as strings.

Any help would be appreciated.



Answer Source

If you are using .NET <= 3.5 the overload which takes an IEnumerable(Of T) is not available. You have to create an array first and use this overload:

 retString = String.Join("</li><li>", uniqueCC2.ToArray())

Side-Note: if you want to wrap the strings in <li>str</li> you should not use String.Join but modify the Select in this way:

Select String.Format("<li>{0}</li>", d.Field(Of String)("CageCardID"))).Distinct()

Then the final string would be created in this way

Return String.Concat( uniqueCC2 ) ' no further delimiter needed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download