I have a list (returned from database) and I have a combo box which I am populating with a list, I am doing this because the ComboBox can be populated from a range of data sources.
I need to convert the IList(Of Object) into a List(Of String).
The Object has an override on the ToString method.
Please can anyone advise on this one?
If you have a IList(Of Object), like this:
Dim objects As IList(Of Object) = New List(Of Object)({"test", "test2"})
You can add the items in that list to a ComboBox, directly, like this:
ComboBox1.Items.AddRange(objects.ToArray())
There is no need to first convert it to a List(Of String) since the ComboBox automatically calls the ToString method for you on each item in the list. However, if you really need to convert it to a List(Of String), you can do it like this:
Dim strings As List(Of String) = objects.Select(Function(x) x.ToString()).ToList()
Or, if you don't want to use the LINQ extension methods, you could do it the old-fashioned way, like this:
Dim strings As New List(Of String)()
For Each i As Object In objects
strings.Add(i.ToString())
Next
Use linq:
Private Function ConvertToListOfString(lstObject As IList(Of Object)) As List(Of String)
Return lstObject.Select(Function(e) e.ToString()).ToList()
End Function
Related
I have an extension method that works great in converting an object to my form object.
'Copy an object to a form object
<Extension()> _
Public Function FromModel(ToObject As BaseFormObject, ByRef FromObject As Object) As Boolean
ToObject = FromObject
Return True
End Function
I want to do the same thing for a list of objects.
'Copy a list of objects to form objects
<Extension()> _
Public Function FromModelList(ToList As List(Of BaseFormObject), ByRef FromList As List(Of Object)) As Boolean
For Each FromItem As Object In FromList
'Create a new BaseFormObject for every item in FromList, Add it to our From List
Dim newFormObject = New BaseFormObject()
newFormObject.FromModel(FromItem)
ToList.Add(newFormObject)
Next
Return True
End Function
Creating a new List(Of BaseFormObject) does not give me access to the method "FromModelList." What is the proper way to go about doing this?
Your code works fine.
I created this code:
Dim lst As New List(Of BaseFormObject)
I got the extension member when I typed in lst.
I'm going to go out on a limb here and suggest that you're not actually instantiating a List(Of BaseFormObject), but instead something like List(Of ActualFormObject) where ActualFormObject inherits from BaseFormObject.
So if I use this code:
Dim lst As New List(Of ActualFormObject)
Then you don't get the extension member. If that's what you're hoping for, then it's easy to fix.
Change your code to this:
<Extension()> _
Public Function FromModelList(Of T As {New, BaseFormObject})(ToList As List(Of T), ByRef FromList As List(Of Object)) As Boolean
For Each FromItem As Object In FromList
'Create a new BaseFormObject for every item in FromList, Add it to our From List
Dim newFormObject = New T()
newFormObject.FromModel(FromItem)
ToList.Add(newFormObject)
Next
Return True
End Function
Then you get the extension member on lists of sub-classes.
Say I have two dictionaries:
Dim dict1 as new dictionary(Of Integer, String)
Dim dict2 as new dictioanry(Of customType, customtype2)
I want to convert them to a list in a method and return a list of the argued dictionary value type. So....
Public Function DictToListConverter(ByVal argDict as Dictionary(Of Object, Object), ByVal argType as Type) **What goes here.
I know I can just cast the return on the calling routine, but that is not the best solution. I would not like to return a custom class which contains the values.In other words I'm looking for a way to do the following:
Pass in dictionary(Of Integer, String) and get a return of List(Of String)
at the same time, if I pass in a dictionary (of String, Boolean) then the function should return List(of Boolean)
It is looking like this is not possible and I either have to use class / struct, or just cast the object in the calling routine. Just wanted to get a verification on whether or not this request is possible.
Again, thanks!
Assuming you're using .Net 3.5 or later you can do that with the following...
Public Function DictToListConverter(Of TKey, T)(dict As Dictionary(Of TKey, T)) As List(Of T)
Return dict.Select(Function(i As KeyValuePair(Of TKey, T)) i.Value).ToList()
End Function
You need to use List(Of Object), or ArrayList, which is more or less the same.
I'm trying to use a variable that is simply a list of a list of strings.
I've declared it as follows:
Dim iRows As New List(Of List(Of String))
Then I'm trying to pass it as a parameter to another method and I've defined the method as follows:
Public Sub Import(ByVal Rows As IList(Of IList(Of String)))
For Each Row As IList(Of String) In Rows
ImportRow(Row)
Next
End Sub
Unfortunately, when I try to run that code I get the following error where it tries to pass my variable to my method.
System.InvalidCastException was unhandled by user code
Message="Unable to cast object of type 'System.Collections.Generic.List1[System.Collections.Generic.List1[System.String]]' to type 'System.Collections.Generic.IList1[System.Collections.Generic.IList1[System.String]]'."
When I change the method definition to use the types rather than the interfaces as follows, it works.
Public Sub Import(ByVal Rows As List(Of List(Of String)))
For Each Row As IList(Of String) In Rows
ImportRow(Row)
Next
End Sub
So, is it not possible to use generics with interfaces in this way? It works fine as long as I'm not nesting them.
Yes, it is possible to create an IList(Of IList(Of String)) - but a List(Of (List(Of String)) isn't one. Consider that in the latter case you could call
listOfLists.Add(arrayOfStrings)
as a string array implements IList(Of String).
Basically this is exactly the same as considering an IList(Of Fruit) and a List(Of Banana) - a bunch of bananas isn't a fruit-bowl, because you can't add an apple to it.
In your case, you'd need to create a List(Of IList(Of String)) instead - or declare an IList(Of List(Of String)).
Now interestingly, you could use a List(Of List(Of String)) as an IEnumerable(Of IEnumerable(Of String)) in .NET 4 due to generic covariance and contravariance - IEnumerable(Of T) is covariant in T. However, IList(Of T) is invariant.
Generic covariance and contravariance is a tricky topic. Eric Lippert has written a great deal about it - using C# as the language rather than VB, but hopefully you can still understand it.
Start by declaring iRows like this:
Dim iRows As New List(Of IList(Of String))
Then, when you add a new List(Of String) to iRows, it will implicitly cast appropriately.
Try the following change:
Public Sub Import(ByVal Rows As List(Of List(Of String)))
For Each Row As List(Of String) In Rows
ImportRow(Row)
Next
End Sub
There doesn't appear to be a need to cast from List to IList.
How would I make use of a List(of String) in a structure in vb.net. for example
Structure examplestrut
Public exampleslist As List(Of String)
End Structure
How would I call exampleslist.add("example 1")?
Like this:
Dim myStruct as ExampleStruct
myStruct.exampleList = new List(Of String)()
myStruct.exampleList.Add("Hi there!")
Its also worth mentioning that if you already have a 'myStruct' declared earlier in the program and you need to empty it, you use
myStruct.exampleList = new List(Of String)()
rather than
myStruct.exampleList.Clear()
I want to create a generic list - but I want to specify the type at runtime - is there a way I can do this? using reflection perhaps?
Something like this...
Public Shared Sub create(ByVal t As Type)
Dim myList As New Generic.List(Of t)
End Sub
Thanks in advance
James
If callers know the type, you can make the method itself generic:
Public Shared Sub create(Of t)()
Dim myList As New Generic.List(Of t)
End Sub
If callers do not know the type, you'll have to resort to reflection - see the accepted answer to this question for more information.
I have a function to do exactly that:
Public Shared Function CreateList(Of T)(ByVal ParamArray items() As T) As List(Of T)
Return New List(Of T)(items)
End Function
For instance, I can create a list of integers by doing this:
dim L as list(of Integer) = CreateList(1,2,3,4,5)
Or create a list of, say, textboxes:
dim L as list(of TextBox) = CreateList(txtPhone1, txtPhone2, txtPhone3)
Or in general, any type.