|
-
Mar 5th, 2023, 02:33 AM
#1
Thread Starter
Hyperactive Member
Strings Array? Collection? or List? Which one to use and how?
Hi. Niya, This guy, encouraged me to overcome my embarrassment to post this thread cause It was out of private-message discussion. I might be a bit rusty in VB.NET so please do not judge me.
This thread can be divided in 2 ways of question making:
1) Can you redirect me topic links/snippets/codebank which covers making and working with different types of variables?
I already read Learn.Microsoft I know it is an elementary stuff but I always lack in principles (and also in english).
2) Or answer my questions individually here:
Lets begin with declaring lots of strings you want to add members to them. I saw somewhere
Code:
Dim BunchOfStrings() As String = {}
But there's no .Add or .Insert or something else to add a member.
Meanwhile is this particular way of declaring, it does:
Code:
Private BunchOfStrings As New Collection()
Why it should be private? Why it should be at the beginning right after class definition?
Also in this way:
Code:
Dim names As List(Of String) = {"John", "Mike"}.ToList
you can also add members like
But you may not get the entire list length like before .Length method (or even Len() ).
The goal is to read a CSV file and bypass the "put-them-all-in-a-DGV" stage and put them all in a 1 dimension or even multi dimension string, take its length, call a specific cell/member... Sounds simple at first, nightmare for me.
* I'm cool with different dictations based on different types in VB.NET. I wanna know... I want to learn
* I also want to do these add, remove, length, min, max, etc. supported-built-in functions on Strings, Bytes and maybe other types of variables (which I may deal with soon)
Last edited by pourkascheff; Mar 5th, 2023 at 02:37 AM.
-
Mar 5th, 2023, 03:05 AM
#2
Re: Strings Array? Collection? or List? Which one to use and how?
There's an awful lot of unrelated stuff here. Part of your problem is obviously that you treat multiple issues as one. You need to break your issues down into parts and address each part individually. The more basic the issue, the more likely you will find specific information to address it. The more complex the issue, the less likely anyone else has encountered exactly the same thing. This thread really ought to be at least three but probably more individual threads.
Firstly, arrays are more efficient than collections - collections use arrays internally - so you should use an array where they are appropriate. Arrays are fixed-length so you should generally only use them when the number of items you will be working with will not change. If you need to add or remove items, use a collection.
That said, never use a Collection object. That type is a holdover from VB6 and has no place in new VB.NET code. .NET has numerous specialised collection types so use the one most appropriate to the situation. If you need what amounts to a dynamic array, use a List(Of T). If you have some default items to create a List(Of T) with then the proper way to do that is like so:
vb.net Code:
Dim names As New List(Of String) From {"John", "Mike"}
Regardless of the type of object, if you need to access it in multiple methods or multiple calls to the same method then you almost certainly need to assign it to a member variable, also know as a field. Like any member, if a field only needs to be accessed within the type it's a member of, it should be declared Private. If it needs to be access outside that type then it should be declared Public. If you need to make a field Public, you should use a property. You might use an auto-property, whether the getter and setter are implicit, or you can specify the getter and setter explicitly and also declare a Private backing field.
There's never a need to put data into a DataGridView unless the user needs to see it. If you are reading tabular data, e.g. from a CSV, and you want to populate a List(Of T) then you should start by declaring a type that represents a single record, so it will have a property for each column in the data. For instance, you might declare a Person class with GivenName and FamilyName properties. You would then create a List(Of Person). As you read the data, you create a Person object, populate its properties with the data from the record you just read and then add the item to the list, e.g.
vb.net Code:
Private people As New List(Of Person)
Private Sub LoadPeople(filePath As String)
Using parser As New TextFieldParser
Do Until parser.EndOfStream
Dim fields = parser.ReadFields()
people.Add(New Person With {.GivenName = fields(0), .FamilyName = fields(1)}
Loop
Next
End Sub
-
Mar 6th, 2023, 10:00 AM
#3
Thread Starter
Hyperactive Member
Re: Strings Array? Collection? or List? Which one to use and how?
Based on your volume of reply, now I get how vast and unrelate it is.
Part of quest was this matter in which how small principle things - to take care of - affects your way of living massively. For instance I was wondering for a long time what (if any) the difference is between the
Code:
Dim myString() as String
and
Code:
Dim myString as String()
They may work most of the time but not always, Be careful newbies.
So let's break down this thread to smaller things as jmcilhinney asked. I will dial a number next to my question(s). For some reasons I guess working with non-strings would be easier so let's begin:
1) Consider you want mathematically add new members to make {0, 1, 2, ..., 100} via a simple "for" then show them all at once in a messagebox, then show the length 101 in another message. Regarding to previous knowledge first part could be (or have to be) this:
Code:
Public Numero As New List(Of Integer)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 0 To 100
Numero.Add(i)
Next
'JOIN FUNC THEN LENGTH
End Sub
In the commented line we wanted to do a
Dim Str As String() = {}
For i = 0 To Numero.Length - 1 'Loop from the beginning to the end
Str = Str & Join(Numero(i).ToString, ", ") 'Make a sequence
Next
MsgBox(Str.ToString) 'Which could fail since Str. and Str(). could be different
MsgBox(Numero.Length)
But syntax errors happen (That's why I didn't put it in a code box). See? Simple goals, difficult implementation for me
Errors list respectively in lines:
- 'Length' is not a member of 'System.Collections.Generic.List(Of Integer). which he's right. Also there are fewer useable methods this way
- Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Well, CObj(Something) could rectified the matter but it isn't the remedy is it? Other errors won't let the app to run anyways to test it.
- 'Length' is not a member of 'System.Collections.Generic.List(Of Integer). Same as first error.
-
Mar 6th, 2023, 10:14 AM
#4
Re: Strings Array? Collection? or List? Which one to use and how?
Dim Str As String() = {}
has several errors, in this case. For one thing, it is best to avoid Str as a variable name. It at least WAS a method, though I can't recall whether or not it still is. Safer just to use a different name.
However, that's a string array. You are creating a string via concatenation, not a string array. Just a single string, no array. That's probably what the source of the errors is.
Of course, with using String.Join, you don't need the concatenation, or the loop. The whole purpose of that method is to join an array of strings together into a single string. You have an array of strings (actually, you have a List(of String), but a List can be turned into an array with .ToArray), so you are just creating a single string from it using .Join. It would look somewhat like this, though not exactly:
Code:
Dim yourString = String.Join(", ", Numero.ToArray)
That makes a few assumptions that are not quite correct. For one thing, it would assume that Numero is a List(of String), which it is not, but that's close.
Of course, you could join them together via concatenating in a loop, but you'd still be creating just one string:
Code:
Dim yourString As String 'NOT As String(), just As String.
For each itm in Numero
yourString &= itm.ToString & ", "
Next
This won't end up looking right, as written, because it will put a trailing comma after the last element, which will look bad. Therefore, the Join approach is not just smaller and faster, but also will look better. Fixing up the loop to look better would take a few more lines.
My usual boring signature: Nothing
 
-
Mar 6th, 2023, 10:15 AM
#5
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by pourkascheff
1) Consider you want mathematically add new members to make {0, 1, 2, ..., 100} via a simple "for" then show them all at once in a messagebox, then show the length 101 in another message. Regarding to previous knowledge first part could be (or have to be) this:
Code:
Public Numero As New List(Of Integer)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 0 To 100
Numero.Add(i)
Next
'JOIN FUNC THEN LENGTH
End Sub
In the commented line we wanted to do a
Dim Str As String() = {}
For i = 0 To Numero.Length - 1 'Loop from the beginning to the end
Str = Str & Join(Numero(i).ToString, ", ") 'Make a sequence
Next
MsgBox(Str.ToString) 'Which could fail since Str. and Str(). could be different
MsgBox(Numero.Length)
But syntax errors happen (That's why I didn't put it in a code box). See? Simple goals, difficult implementation for me
Errors list respectively in lines:
- 'Length' is not a member of 'System.Collections.Generic.List(Of Integer). which he's right. Also there are fewer useable methods this way
- Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Well, CObj(Something) could rectified the matter but it isn't the remedy is it? Other errors won't let the app to run anyways to test it.
- 'Length' is not a member of 'System.Collections.Generic.List(Of Integer). Same as first error.
There are a number of ways you could do this.
You could do this:-
Code:
Dim numbers As New List(Of Integer)
Dim str As String
For i = 0 To 100
numbers.Add(i)
Next
For i = 0 To numbers.Count - 1
str = str & numbers.Item(i)
If i < numbers.Count - 1 Then str = str & ", "
Next
MessageBox.Show(str)
MessageBox.Show(numbers.Count.ToString)
Or this:-
Code:
Dim numbers As New List(Of Integer)
For i = 0 To 100
numbers.Add(i)
Next
MessageBox.Show(String.Join(", ", numbers))
MessageBox.Show(numbers.Count.ToString)
Or this:-
Code:
Dim numbers As Integer() = Enumerable.Range(0, 101).ToArray
MessageBox.Show(String.Join(", ", numbers))
MessageBox.Show(numbers.Count.ToString)
Or this:-
Code:
Dim count As Integer = 101
MessageBox.Show(String.Join(", ", Enumerable.Range(0, count)))
MessageBox.Show(count.ToString())
All of these do the exact same thing.
-
Mar 6th, 2023, 10:22 AM
#6
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by pourkascheff
1) Can you redirect me topic links/snippets/codebank which covers making and working with different types of variables?
I have a frequently asked question thread, here: Visual Basic .NET - Which Collection Should I Use?
 Originally Posted by pourkascheff
2) Or answer my questions individually here:
It seems as though you have been provided some excellent examples, so I will not add anything else.
-
Mar 6th, 2023, 12:52 PM
#7
Thread Starter
Hyperactive Member
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by Shaggy Hiker
Code:
Dim yourString = String.Join(", ", Numero.ToArray)
Definitely gonna use this, sir...
 Originally Posted by Niya
No idea how did I miss this "Count" (length behavior). Browsing in its methods and already fell in love with .Reverse and .Min/.Max
Two short questions right here before closing string/Integer:
1) What's the difference between Numero.Clear() and Numero.RemoveAll()? The latter was more tricky and no idea what does the argument wants (Trust me, I read them. But Func and sub? Really? In Arg?)
2) Consider you have a huge (I mean HUGE) 1 dim matrix you've stored. There's no .Dispose like before, is there? I just got used to be more efficient lately and making it a fun hobby. Let me be loyal to it.
 Originally Posted by dday9
You know what? Gonna visit FAQ section more often now on... You just simply reduced this thread a dozen of replies since my few questions already answered. RESPECT
Last edited by pourkascheff; Mar 6th, 2023 at 01:01 PM.
-
Mar 6th, 2023, 01:06 PM
#8
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by pourkascheff
1) What's the difference between Numero.Clear() and Numero.RemoveAll()? The latter was more tricky and no idea what does the argument wants (Trust me, I read them. But Func and sub? Really? In Arg?)
Clear removes all items from the list, RemoveAll is a function that allows you to specify another function as a way to filter which items to remove...
Code:
Dim numbers As New List(Of Integer) From {3, 4, 5, 6, 7, 8, 9, 34}
numbers.RemoveAll(
Function(number As Integer)
Return number Mod 2 = 0
End Function)
would remove all the even numbers from the list, but any odd numbers would remain.
 Originally Posted by pourkascheff
2) Consider you have a huge (I mean HUGE) 1 dim matrix you've stored. There's no .Dispose like before, is there? I just got used to be more efficient lately and making it a fun hobby. Let me be loyal to it.
You only need .Dispose if the variable you are using is dealing with resources outside of .Net's control e.g. DataBase connections, File Handles etc. Arrays, Lists etc, are just memory - the Garbage Collector will deal with these when they are no longer being used.
-
Mar 6th, 2023, 01:07 PM
#9
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by pourkascheff
1) What's the difference between Numero.Clear() and Numero.RemoveAll()? The latter was more tricky and no idea what does the argument wants (Trust me, I read them. But Func and sub? Really? In Arg?)
Clear removes all items unconditionally, but RemoveAll removes all items that meet a condition. For example:-
Code:
Dim numbers As List(Of Integer) = Enumerable.Range(1, 20).ToList
'Removes all even numbers
numbers.RemoveAll(Function(item) Not CBool(item Mod 2))
The above removes only even numbers from the list.
 Originally Posted by pourkascheff
2) Consider you have a huge (I mean HUGE) 1 dim matrix you've stored. There's no .Dispose like before, is there? I just got used to be more efficient lately and making it a fun hobby. Let me be loyal to it.
I'm not sure what you're talking about here. Lists, Arrays and Collections have never had a Dispose method.
-
Mar 6th, 2023, 01:38 PM
#10
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by PlausiblyDamp
Clear removes all items from the list, RemoveAll is a function that allows you to specify another function as a way to filter which items to remove...
Code:
Dim numbers As New List(Of Integer) From {3, 4, 5, 6, 7, 8, 9, 34}
numbers.RemoveAll(
Function(number As Integer)
Return number Mod 2 = 0
End Function)
would remove all the even numbers from the list, but any odd numbers would remain.
Oh wow.....we just came up with the EXACT same example independently. If I were superstitious, I'd be uneasy right now. That is freaky as hell!
We even quoted him exactly, my God what is happening!
-
Mar 6th, 2023, 01:42 PM
#11
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by Niya
Oh wow.....we just came up with the EXACT same example independently. If I were superstitious, I'd be uneasy right now. That is freaky as hell!
We even quoted him exactly, my God what is happening!
That is a bit uncanny! Especially the identical quoting!
-
Mar 6th, 2023, 01:48 PM
#12
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by PlausiblyDamp
That is a bit uncanny! Especially the identical quoting!
Looking at it further, even the way we structured our posts were identical. We both describe the difference between Clear and RemoveAll in one line, then showed code and then described what the code did on one line. I almost wanna start believing in spiritual stuff. How does that even happen.
-
Mar 6th, 2023, 03:08 PM
#13
Thread Starter
Hyperactive Member
Re: Strings Array? Collection? or List? Which one to use and how?
I was wondering can I do the reverse of
 Originally Posted by Shaggy Hiker
Code:
Dim yourString = String.Join(", ", Numero.ToArray)
(Literally vice versa) That I came up with AddRange method.
Code:
Dim LinearString As String = "Hello,World,Let,It,Be,Our,Linear,String,Example"
Dim DiscreteString As New List(Of String)
DiscreteString.AddRange(Split(LinearString, ","))
Interesting field... never got it that much serious but it is...
Following on this thread: I'm going to test a list/collection of UserControls tonight and see what happens while our lads are practicing their telepathic skills. =)
Last edited by pourkascheff; Mar 6th, 2023 at 03:28 PM.
-
Mar 6th, 2023, 03:20 PM
#14
Re: Strings Array? Collection? or List? Which one to use and how?
 Originally Posted by Niya
Looking at it further, even the way we structured our posts were identical. We both describe the difference between Clear and RemoveAll in one line, then showed code and then described what the code did on one line. I almost wanna start believing in spiritual stuff. How does that even happen.
Technically, if coincidences did NOT happen, it would be far stranger.
My usual boring signature: Nothing
 
-
Mar 6th, 2023, 04:00 PM
#15
Re: Strings Array? Collection? or List? Which one to use and how?
Why bother initialising the list by hard coding a string, then splitting this string to generate an array, and then adding it.
You can simply initialise a list of strings the same way I did in my post, just use strings instead of integers.
Splitting a string will be slower, and will use more memory as well.
-
Mar 7th, 2023, 01:23 AM
#16
Thread Starter
Hyperactive Member
Re: Strings Array? Collection? or List? Which one to use and how?
Nah mate, the goal is to read a file entirely as string (like a csv, there hundreds of ways to do this first step), then perform a sort of logical operation on every member, return a hash, get its min/max, put them all in a DGV for instance.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|