Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 847
  • Last Modified:

Need help with "Unable to cast object" error

I am trying to create an arraylist of unique elements from two arraylists using Vb.net & linq but I get the following error on the last line of the embedded code.

"Unable to cast object of type '<DistinctIterator>d__81`1[System.Object]' to type 'System.Collections.ArrayList'."

this is my code:
Dim arr1 as arraylist=some mixture of integers and strings      
Dim arr2 as arraylist=some mixture of integers and strings    
Dim arr As New ArrayList
Dim DistinctArray As New ArrayList
Dim pos As Integer
Dim str As String

arr.AddRange(arr1)
arr.AddRange(arr2)
DistinctArray = (From s In arr Select s).Distinct

Open in new window

I am not really that familiar with linq so I'd love any help.
0
NevSoFly
Asked:
NevSoFly
1 Solution
 
Luis PérezSoftware Architect in .NetCommented:
Your problem is that the results from the Linq clause is not an ArrayList, so it cannot cast right.

Try this:
Dim arr1 as arraylist=some mixture of integers and strings      
Dim arr2 as arraylist=some mixture of integers and strings    
Dim arr As New ArrayList

arr.AddRange(arr1)
arr.AddRange(arr2)
Dim DistinctArray = (From s In arr Select s).Distinct

Open in new window


From this point, you can manage DistinctArray in the same way as it was an ArrayList. But don't declare it explicitly as ArrayList or you'll get the error.

Hope that helps.
0
 
NevSoFlyAuthor Commented:
Thanks, your code worked.  After playing around with it I did manage to get the arraylist result I originally wanted.  Maybe this will help someone else out.

Dim arr1 as arraylist=some mixture of integers and strings      
Dim arr2 as arraylist=some mixture of integers and strings  
Dim DistinctArray As New ArrayList  
Dim arr As New ArrayList

arr.AddRange(arr1)
arr.AddRange(arr2)
DistinctArray.AddRange((From s In arr Select s).Distinct.toList)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now