Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to find the first unused number in listbox, that contains random numbers, but im getting this error. Could you maybe tell me what am i missing here?

'Unable to cast object of type 'ObjectCollection' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'.'

What I have tried:

 Dim FB As Integer = Enumerable.Range(0, Integer.MaxValue).Except(ListBox1.Items).FirstOrDefault()
MessageBox.Show(FB)
Posted
Updated 5-May-20 13:32pm
Comments
Dave Kreskowiak 5-May-20 22:37pm    
What are you really trying to do with this? All you're doing is returning an enumerator over a range of 2.147Billion - 1 integers, and that really doesn't seem very useful at all.

1 solution

Try to cast the object collection items back to integers:
VB.NET
Dim FB As Integer = Enumerable.Range(0, Integer.MaxValue).Except(ListBox1.Items.Cast(Of Integer)()).FirstOrDefault()

It may not work, though, depending on how you populated the listbox.

Edit: after some second toughts, loading into memory a range of over 2 billions of integers may not be the best idea. You could try this instead:
VB.NET
Public Function GetFirstAvailable() As Integer
   Dim list as New List(Of Integer)(ListBox1.Items.Cast(Of Integer)())
   For i As Integer = 0 To Integer.MaxValue
      If Not list.Contains(i)
         Return i
      End If
   Next
   Return -1 '' Have a way to tell there wasn't any available positive integer, even if it is not likely
End Function

Dim FB As Integer = GetFirstAvailable()
 
Share this answer
 
v3
Comments
Richard Deeming 7-May-20 12:06pm    
Enumerable.Range doesn't load a list into memory; it's evaluated lazily.

Except does store a copy of all of the distinct items from the second list, which is essentially what your GetFirstAvailable method is doing.
Reference Source[^]

If you used ListBox1.Items.Cast(Of Integer).Except(Enumerable.Range(0, Integer.MaxValue)), then you'd have a memory problem. :)

NB: You need to move the Return -1 outside of the For loop.
phil.o 8-May-20 5:57am    
Thanks Richard, I corrected the placement of the return statement. Thanks also for the precisions about the Enumerable.Range behaviour.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900