|
-
May 11th, 2016, 10:04 AM
#1
Trying to understand Collections
Hi Guys,
After being admonished yet again by jmcilhinney I'm trying to understand Collections.
I can use the code: -
Code:
Dim Col1 As New Microsoft.VisualBasic.Collection()
without much of a problem.
But now I'm trying to use 'Pairs' of data. Collection as above will accept a pair of data, but I can't find how to retrieve both.
So I looked at: -
Code:
Dim Col2 As New Hashtable()
Which it seems is more designed towards 'Pairs', but again, I can submit a pair of data and they're accepted, but again I can't find how to retrieve 'em.
Setting a breakpoint after adding a pair of data to either type of collection I can see in the 'Locals' window that both data are there, in my case they're listed as 'Key' and 'Value' although the 'key' is an integer and the 'Value' is a string... They're listed as such, so something must be right.
So I'm asking how to retrieve both data, I can only retrieve the 'Key' at the moment.
With a string data and an integer data in Col1 and using : -
Code:
Dat1 = Col1.Item(1)
For example will put the 'String' into the string variable Dat1.
I tried: -
But that failed at runtime... Dat2 as an Int32 was the wrong variable type. I thought maybe it was cleaver and know which data type I was asking for, I did wonder what would happen in that case if both data types were the same.
I tried the same with Col2 with the same result.
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 11th, 2016, 10:22 AM
#2
Re: Trying to understand Collections
The Collection object you're trying to use is actually a holdover from VB6, and it's a fairly simple and "stupid" animal. Most of us have moved on in favor of "Generics" ... where List(of) exists...
Collections aren't type-specific,which means you can throw anything into them. This can be handy, but it can present problems. You can throw a recordset in there for index 1, and then right after that, add a string, and an integer, and a form, and ... quite literally, anything.
Lists on the other hand are type specific, so once you define it and what the list will hold, that's the only thing you can throw in there. so if I have Dim ListONumber as new List(Of Integer) ... I can't do this: ListONumber.Add Form1 ... that will throw an error at compile.
Now, if you want to store things with in a Key/Value pair, then what you likely want is a Dictionary(Of K, T) This allows you to add values of type T, using a key of type K ....
Dim Cards as new Dictionary(Of String, Integer)
Cards.Add("AS", 11)
Cards.Add("10S", 10)
I can retrieve the value in either way:
Cards(0) -- Ace of spades
Cards("AS") -- also Ace of spades
The advantage here though, is that unlike the Collection object, the Dictionary does expose the Keys as a collection field (not Collection) that you can iterate through.
Code:
For Each k As String In Cards.Keys
MessageBox.Show(k)
Next
There is also a Cards.Values collection you can run through as well...
-tg
-
May 11th, 2016, 10:26 AM
#3
Re: Trying to understand Collections
These are the general rules of collections that I follow
If I need to store values who's size is fixed(ie it cannot grow or shrink) then I use an array.
If I need to store values who's size is not fixed then I will either use a List(Of T), Queue(Of T), or Stack(Of T). A List represents a generic dynamic sized collection where you can add/remove items at any index. A Queue represents a FIFO(first-in-first-out) collection where items that are added in first are the first to be removed. A Stack represents a LIFO(last-in-fast-out) collection where the items that are added in last are the first to be removed.
If I need to store pairs with a unique key then use a Dictionary(Of TKey, TValue).
If I need to store pairs without a unique key then create a class and use an appropriate collection to store the classes.
-
May 11th, 2016, 10:36 AM
#4
Re: Trying to understand Collections
 Originally Posted by techgnome
Now, if you want to store things with in a Key/Value pair, then what you likely want is a Dictionary(Of K, T) This allows you to add values of type T, using a key of type K ....
-tg
Thanks for the rapid reply Techgnome,
The 'Key' and 'Value' aspect of Collections just happens to be. All I'm trying to do is keep a pair of data together so that in whatever order I pull 'em back out they're still the right pair.
I'm going to have a play with your suggestion... Sadly not just now... SWMBO has other ideas.
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 11th, 2016, 11:12 AM
#5
Re: Trying to understand Collections
 Originally Posted by dday9
If I need to store pairs without a unique key then create a class and use an appropriate collection to store the classes.
...if I understand what you are saying here I would split it into two rules...
If I need to store LOTS and LOTS of pairs without a unique key (that are also mostly read-only) then create a structure and use an appropriate collection to store the structure.
If I need to store LESS then LOTS and LOTS of pairs without a unique key then create a class and use an appropriate collection to store the classes.
-
May 11th, 2016, 12:17 PM
#6
Re: Trying to understand Collections
 Originally Posted by Poppa Mintin
Thanks for the rapid reply Techgnome,
The 'Key' and 'Value' aspect of Collections just happens to be. All I'm trying to do is keep a pair of data together so that in whatever order I pull 'em back out they're still the right pair.
I'm going to have a play with your suggestion... Sadly not just now... SWMBO has other ideas.
Poppa.
The reason it's so confusing is VB chose the wrong name when it chose "Collections", and it got more confusing when MS 'fixed' the definition in .NET. The word "collection" was a bad idea on both counts.
The rest of the programming world calls this type of data structure an "associative array", "hashtable", or "dictionary". All of them have the sense of "a value is associated with a unique key, and the key is used to reference values." Sometimes VB is different because it simplifies concepts. In this case, I think VB was different for the sake of being different. (We're talking the context of VB6 and previous, here.)
When MS laid the foundations for .NET, they decided they should probably name things what non-.NET developers would understand. So we end up with a lot of words meaning weird things.
- A 'collection' to .NET is just "a variable that represents many values". For almost all intents and purposes, IEnumerable is the /actual/ abstract concept of a .NET collection. But because of the former statement, .NET has a 'System.Collections' and 'System.Collections.Generic' namespace.
- A CollectionBase class exists. It's purpose isn't explicitly clear, and if you look through the classes that derive from it you won't find many familiar types. It's vestigal and obsolete. It's not even a good base collection type for anything but a list. Whoops.
- The VB Collection type is implemented in the VB6 compatibility libraries. It's there to help interviewers distinguish between .NET developers and people who write VB6 in .NET.
- MS recognized their error, and since about 2005 it's safe to say "Almost no .NET collection derives from CollectionBase at all, but we're stuck with calling these things 'collection types'."
- Because in the Microsoft world, nothing can ever be deleted, even if it's 30 years old and sets your computer on fire when used, almost 50% of the .NET collection types are obsolete traps with new, better replacements, and any time you spend studying them is a waste. Which 50%? Mostly what lives in System.Collections, the MOST OBVIOUS NAMESPACE.
Everyone else is happy calling the whole topic "data structures" and most other languages weren't arrogant enough to assert they could make one base type that represents all data structures. IEnumerable is the closest we get to that concept.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 11th, 2016, 12:34 PM
#7
Re: Trying to understand Collections
Ya know what guys... I'm going back to putting two data together with a divider, probably a | then separate 'em when I need 'em.
Simple.
Thanks for your time guys...
Poppa.
Szlamany, I'm sorry, you might as well be telling me in Greek... I didn't really understand what you're telling me at all.
Pop.
Along with the sunshine there has to be a little rain sometime.
-
May 11th, 2016, 12:45 PM
#8
Re: Trying to understand Collections
 Originally Posted by Poppa Mintin
Thanks for the rapid reply Techgnome,
The 'Key' and 'Value' aspect of Collections just happens to be. All I'm trying to do is keep a pair of data together so that in whatever order I pull 'em back out they're still the right pair.
I'm going to have a play with your suggestion... Sadly not just now... SWMBO has other ideas.
Poppa.
So it's just a pair of values? not a key/value pair?
Two things: 1) create a class that has two properties Thing1, Thing2 ... then make a List(of Things1_2) ... or 2) use a tuple and a List (Of Tuple) ...
 Originally Posted by Sitten Spynne
The reason it's so confusing is VB chose the wrong name when it chose "Collections", and it got more confusing when MS 'fixed' the definition in .NET. The word "collection" was a bad idea on both counts.
The rest of the programming world calls this type of data structure an "associative array", "hashtable", or "dictionary". All of them have the sense of "a value is associated with a unique key, and the key is used to reference values." Sometimes VB is different because it simplifies concepts. In this case, I think VB was different for the sake of being different. (We're talking the context of VB6 and previous, here.)
When MS laid the foundations for .NET, they decided they should probably name things what non-.NET developers would understand. So we end up with a lot of words meaning weird things.
- A 'collection' to .NET is just "a variable that represents many values". For almost all intents and purposes, IEnumerable is the /actual/ abstract concept of a .NET collection. But because of the former statement, .NET has a 'System.Collections' and 'System.Collections.Generic' namespace.
- A CollectionBase class exists. It's purpose isn't explicitly clear, and if you look through the classes that derive from it you won't find many familiar types. It's vestigal and obsolete. It's not even a good base collection type for anything but a list. Whoops.
- The VB Collection type is implemented in the VB6 compatibility libraries. It's there to help interviewers distinguish between .NET developers and people who write VB6 in .NET.
- MS recognized their error, and since about 2005 it's safe to say "Almost no .NET collection derives from CollectionBase at all, but we're stuck with calling these things 'collection types'."
- Because in the Microsoft world, nothing can ever be deleted, even if it's 30 years old and sets your computer on fire when used, almost 50% of the .NET collection types are obsolete traps with new, better replacements, and any time you spend studying them is a waste. Which 50%? Mostly what lives in System.Collections, the MOST OBVIOUS NAMESPACE.
Everyone else is happy calling the whole topic "data structures" and most other languages weren't arrogant enough to assert they could make one base type that represents all data structures. IEnumerable is the closest we get to that concept.
hehehe... now try to explain tuples... 
-tg
-
May 11th, 2016, 01:22 PM
#9
Re: Trying to understand Collections
 Originally Posted by Poppa Mintin
Ya know what guys... I'm going back to putting two data together with a divider, probably a | then separate 'em when I need 'em.
Simple.
Thanks for your time guys...
Poppa.
Szlamany, I'm sorry, you might as well be telling me in Greek... I didn't really understand what you're telling me at all.
Pop.
This is a bad idea. Just because you do not understand something does not justify excluding it all together, in fact it should prompt you to learn more about it especially since now 3 different member has suggested that you move onto a Dictionary or a List of a custom class depending on your needs. The solution that you are providing requires that you restrict data that a user can enter, not only does it mean that you will need to implement some code to stop the user from entering a pipe symbol(or whichever divider that you use) but it also means that you will be having to do multiple splits on String literals to get your values, this can get inefficient very quickly.
This thread has prompted me to create my very first thread in the FAQ forum titled: Visual Basic .NET - Which Collection Should I Use? I suggest that you take the time to read through each question and see which situation fits your situation and then apply the answer.
In this particular scenario it sounds like want to use the answer to question #6 which reads:
I have a set of values that are pairs, however I don't want either the key or value in the pair to have to be unique. Which collection should I use?
I don't know what your data looks like but you could create a List(Of KeyValuePair(Of String, String)) if you didn't want to write your own class. Here is an example:
Code:
Dim values As New List(Of KeyValuePair(Of String, String))
values.Add(New KeyValuePair(Of String, String)("key1", "value1"))
values.Add(New KeyValuePair(Of String, String)("key1", "value2")) 'Nonunique keys
values.Add(New KeyValuePair(Of String, String)("key2", "value3"))
values.Add(New KeyValuePair(Of String, String)("key3", "value4"))
Console.WriteLine(values.Item(1).Value) 'Print the 2nd item's Value
This solution does not require you to restrict any characters nor does it require you to split String literals.
Edit - techgnome - for a tuple!
-
May 12th, 2016, 05:50 AM
#10
Re: Trying to understand Collections
Hi Dday,
1.
This is a bad idea. Just because you do not understand something does not justify excluding it all together, in fact it should prompt you to learn more about it especially since now 3 different members have suggested that you move onto a Dictionary or a List of a custom class depending on your needs.
I agree, but when I've spent hours of my vacation trying to find an answer to my original question, (with still no actual answer as yet) getting on with my project by using something that I understand and which works very well and took less than five minutes to implement, seems reasonable to me.
2.
The solution that you are providing requires that you restrict data that a user can enter, not only does it mean that you will need to implement some code to stop the user from entering a pipe symbol(or whichever divider that you use) but it also means that you will be having to do multiple splits on String literals to get your values, this can get inefficient very quickly.
Who mentioned User Input ? The only user is myself, I don't believe I've ever used pipe in any document, or anything else for that matter. One split is hardly 'Multiple'.
3.
This thread has prompted me to create my very first thread in the FAQ forum.
I suggest that you take the time to read through each question and see which situation fits your situation and then apply the answer.
In this particular scenario it sounds like want to use the answer to question #6
I've read through your very interesting thread, paying particular attention to #6.
Sadly, even that doesn't answer my original question.
4.
I don't know what your data looks like...
In this instance I've not posted any code, normally I would but I don't believe adding code would actually help here. And it would most likely result in more adverse criticism from jmcilhinney.
I've spent several hours, prior to asking my question, reading through MSDN and looking through articles thrown up by Google, none of which answer my question, they do however nearly all use 'Console.WriteLine' and trying to get to my answer using what I can make out of that has wasted even more time.
Poppa.
Last edited by Poppa Mintin; May 12th, 2016 at 05:52 AM.
Reason: Corrected spacing. YET AGAIN.
Along with the sunshine there has to be a little rain sometime.
-
May 12th, 2016, 06:06 AM
#11
Re: Trying to understand Collections
Seems every thread now - even those with the simplest of questions - becomes a huge multi-post opinions overflowing - going off the rails...
And the OP still has no good answer to his question.
What is the simplest way that the OP can get pairs of items listed?
If you know the upper limit it's just a two-dimension array - right?
SomeListOfPairs(100,1)
Gives you 0 to 100 items with a ", 0)" and ", 1)" pair of entries.
Now - not knowing the upper-limit what is the simplest way to have pairs of entries?
This should be a one-post answer - let's see what we get...
-
May 12th, 2016, 06:31 AM
#12
Re: Trying to understand Collections
 Originally Posted by szlamany
What is the simplest way that the OP can get pairs of items listed?
This should be a one-post answer - let's see what we get...
Szlamany, and everyone else...
This isn't the question !
My question has always been:
So I'm asking how to retrieve both data, I can only retrieve the 'Key' at the moment.
Please note the word 'Retrieve'.
Retrieve
(rɪˈtriv)
n. v.t.
1. to recover or regain.
2. to bring back to a former and better state; restore.
3. to make amends for; make good; repair: to retrieve an error.
4. to recall to mind.
5. (of hunting dogs) to fetch (killed or wounded game).
6. to rescue; save.
7. (in tennis, handball, etc.) to make an in-bounds return of (a difficult shot).
8. to locate and read (data) from computer storage, as for display on a monitor.
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 12th, 2016, 06:44 AM
#13
Re: Trying to understand Collections
 Originally Posted by Poppa Mintin
Thanks for the rapid reply Techgnome,
The 'Key' and 'Value' aspect of Collections just happens to be. All I'm trying to do is keep a pair of data together so that in whatever order I pull 'em back out they're still the right pair.
Since you are only storing pairs of data - as you clearly say here - why is one a key and one a value in your requirements?
-
May 12th, 2016, 06:52 AM
#14
Re: Trying to understand Collections
Here is a solution using Tuple.
Code:
'create a list of string, integer
Dim someList As New List(Of Tuple(Of String, Integer))
someList.Add(Tuple.Create("abc", 1))
someList.Add(Tuple.Create("foo", 2))
someList.Add(Tuple.Create("foo", 3))
someList.Add(Tuple.Create("bar", 4))
'show all items in list
For Each t As Tuple(Of String, Integer) In someList
Debug.WriteLine("{0} {1}", t.Item1, t.Item2)
Next
'find one item
Dim findFoo As Tuple(Of String, Integer)
For Each t As Tuple(Of String, Integer) In someList
If t.Item1 = "foo" Then
findFoo = t
Exit For
End If
Next
If findFoo IsNot Nothing Then
Debug.WriteLine("{0} {1}", findFoo.Item1, findFoo.Item2)
End If
-
May 12th, 2016, 06:59 AM
#15
Re: Trying to understand Collections
So of all the options given... which ones don't work and why? If you have the key then surely you can get the data... isn't that what the key is?
Dictionary - has a Key collection you can iterate through... using the keys you can get to the data. now you can retrieve both the key and the value.
List(Of _custom class) - the custom class is a two property object that has Thing1 and Thing2 ... thing1 is the "key" thing2 is the value... a foreach iteration gives you an object with both things... you have your key and value pair
Array(100,1) - put your key in index ,0 and the value in index ,1 ... the two are there together in the same primary index.
List (of Tuple) (or an array of Tuple) - Tuples are an interesting animal in that they can contain any number of related values, you define what they are and how many tuples are needed when you create it...
speaking of Tuples ... here's how easy they are:
Code:
Private Sub Bar()
Dim listOStuff As New List(Of Tuple(Of String, String))
Dim t As New Tuple(Of String, String)("Thing1", "Thing2")
listOStuff.Add(Tuple.Create("Thing1", "Thing2"))
For a = 1 To 50
listOStuff.Add(Tuple.Create("Item" & a.ToString, "Another Item" & a.ToString))
Next
MessageBox.Show(listOStuff.Item(10).Item1, listOStuff.Item(10).Item2)
End Sub
Here I created a list to hold 2-element tuples. I could have used an array as well... I could also create tuples with 3 or 4 or 7 items in it. The tuples could also contain integers, dates, what ever, I just used a string & string for an example.
I add thing1 and thing2 as data points, I then add 50 new tuples with ItemX and Another itemX as the values... I then display the 10th tuple (which should be Item9) and display Item1 (the text "Item9") as the text and Item2 ("Another Item9") as the caption.
-tg
-
May 12th, 2016, 07:15 AM
#16
Re: Trying to understand Collections
My question has always been:
So I'm asking how to retrieve both data, I can only retrieve the 'Key' at the moment.
The direct answer to that question is that you use the Item property of the HashTable and pass in the key as an indexer. See here for a simple example. If that's absolutely all you want then stop reading now.
I think the "run on" nature of the thread, though, has come from the fact that we're not 100% sure of your more general requirement. We're not sure a HashTable's really the best data structure for you to be using (in fact, we're fairly sure there'll be a better one available) and we'd like to give you a little bit more than the simple answer above. But because we've got some unanswered questions about the more general requirement we don't really know what that "little bit more" should look like.
You've averred several time to being admonished by JMc (yeah, he does do that, but you can't fault his knowledge and he has a thoroughly annoying habit of being right ) so I'm guessing there was another thread that lead you to starting to this one. It might be worth providing a link to it. I wouldn't want to encourage everyone to ghoulishly pick over any rows you may have had but it might provide us with a short cut to understanding what your underlying goal is.
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
May 12th, 2016, 07:46 AM
#17
Re: Trying to understand Collections
 Originally Posted by szlamany
Since you are only storing pairs of data - as you clearly say here - why is one a key and one a value in your requirements?
Quote from original post.
Setting a breakpoint after adding a pair of data to either type of collection I can see in the 'Locals' window that both data are there, in my case they're listed as 'Key' and 'Value' although the 'key' is an integer and the 'Value' is a string... They're listed as such, so something must be right.
So I'm asking how to retrieve both data, I can only retrieve the 'Key' at the moment.
I don't have a requirement for a key or for a value... As I said in my original post, when I look in the Debug Locals window, I can see both data, they are Listed as key and value. I thought I explained that if they were a key and a value, they seemed to be the wrong variable types for either.
What I'm after, and what I achieve very easily by concatenation and subsequent split, is the storing of two variables, and keeping them together.
Store like this: -
Code:
Dim Collet As New Microsoft.VisualBasic.Collection()
Collet.Add(a.ToString & "|" & z) 'Store this.
Retrieve like this: -
Code:
z = Collet.Item(1) 'Retrieve.
a = Val(z)
z = z.Substring(InStr(z, "|"))
Where 'a' is an Int32 Variable, and 'z' a String.
Just five lines of code. jmcilhinney complained that I was using an invisible ListBox where (He says... She ?) I should be using a collection... So I'm using a collection, where's the problem ?
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 12th, 2016, 07:48 AM
#18
Re: Trying to understand Collections
Ok - so the method you landed on has no key. "Key" was introduced by collection methods you were trying.
You have no requirement of a key and a value - just two values.
Got it.
-
May 12th, 2016, 08:00 AM
#19
Re: Trying to understand Collections
Here is what I posted before with a few things added. It seems like it would do what you want.
Code:
'create a list of string, integer
Dim someList As New List(Of Tuple(Of String, Integer))
someList.Add(Tuple.Create("abc", 1))
someList.Add(Tuple.Create("foo", 2))
someList.Add(Tuple.Create("foo", 3))
someList.Add(Tuple.Create("bar", 4))
'show all items in list
For Each t As Tuple(Of String, Integer) In someList
Debug.WriteLine("{0} {1}", t.Item1, t.Item2)
Next
'show all items in list v2
For x As Integer = 0 To someList.Count - 1
Dim t As Tuple(Of String, Integer) = someList(x)
Debug.WriteLine("{0} {1}", t.Item1, t.Item2)
Next
'find one item
Dim findFoo As Tuple(Of String, Integer) = someList(0) 'first item in list
Debug.WriteLine("{0} {1}", findFoo.Item1, findFoo.Item2)
For Each t As Tuple(Of String, Integer) In someList
If t.Item1 = "foo" Then 'finds first 'foo'
findFoo = t
Exit For
End If
Next
Debug.WriteLine("{0} {1}", findFoo.Item1, findFoo.Item2)
-
May 12th, 2016, 08:12 AM
#20
Re: Trying to understand Collections
 Originally Posted by FunkyDexter
You've averred several time to being admonished by JMc (yeah, he does do that, but you can't fault his knowledge and he has a thoroughly annoying habit of being right ) so I'm guessing there was another thread that lead you to starting to this one. It might be worth providing a link to it.
Yeah, I know, annoying ain't it ? 
I was trying to give a reply to a guy asking for help, no other replies had been given, although Funky Dexter actually beat me to it... There's nothing worse than waiting forever for an answer to a problem. I get a bit annoyed though when JMc rips into my suggestions, if he's that bothered by my replies, he should answer the guy's question himself. It makes me think I'll stop trying to help.
Poppa.
http://www.vbforums.com/showthread.p...3&goto=newpost
Last edited by Poppa Mintin; May 12th, 2016 at 08:15 AM.
Reason: Link not working.
Along with the sunshine there has to be a little rain sometime.
-
May 12th, 2016, 08:24 AM
#21
Re: Trying to understand Collections
I don't find this worth my time anymore. Generally I would just say good luck and unsubscribe but before I unsubscribe I want to leave you a little message that hopefully others in your situation will read.
I, along with many others, have given you several different solutions to store pairs of data. But when you did not understand how to retrieve the data you just said, thanks but I am going to fall back on what is comfortable because I do not understand how your code works, rather than asking us how it is that you can retrieve the data from the collections(even though techgnome showed how using a Dictionary in post #2 and I showed how using a List in post #9).
Furthermore whenever I tried to elaborate why the idea of using a pipe delimiter was a TERRIBLE idea and suggested alternatives, you get on the defensive and try to justify your solution(without a good justification might I add).
Post #12 is where I decided to draw the line and say screw it. You post the definition of retrieve as if we did not know what the word meant. I guess where I went wrong was I assumed that you knew when you are using a KeyValuePair, whether in a Dictionary like techgnome showed you or in a List like I showed you, that if you wanted the Value property and not the Key property... that you would get the Value property, which by the way... I showed you how to do that in post #9!
-
May 12th, 2016, 08:52 AM
#22
Re: Trying to understand Collections
Oh, so it's not even your own problem you're trying to resolve. Yeah, I can see how going round the houses to try and solve someone else's problem could get kind of frustrating.
You're link doesn't work but I took a quick look through your recent threads and tracked it back to the one about lottery slips and ensuring the same number's not used twice. For reference it's here.
For the record, although JMc might have come across as a bit aggressive, I'm afraid I'd view this as one of those situations where he was annoyingly right. It's generally best not to use UI controls as placeholders for variables because they add all sorts of overhead. But while keeping UI controls out of it would have been better, any solution is better then no solution and I'd still give you a big thumbs up for posting yours.
Anyway, in the case of that problem you don't need key value pairs or any other kind of pair. It just needs a collection (not Collection) of individual numbers. I'd have used a List (of Int). You can reference an item in a List by it's ordinal position so you could use a random number to get the value you want and then use the same number to remove it from the List ready for another pass. I don't have an ide in front of me so I'll get the syntax wrong (if anyone wants to correct my work, feel free) but here's roughly what it would have looked like (it'll probably be closer to C# than VB.Net because that's what I'm used to these days):-
VB.Net Code:
'populate all possible choices into a List List<int> possibleNumbers = new List<int>(); for (int I=1; i<=numPossibleNumbers; i++) possibleNumbers.Add(i); 'Create another list to hold the chosen numbers List<int>chosenNumbers = new List<int> for (int i=1; i<numOfNumberstoPick; i++) { 'I cant for the life of me remember how to generate a random number 'so just pretend Ive generated one called r and its somewhere between 'zero and the length of possibleNumbers 'grab whatever number is at the random position in our list of possibilities chosenNumbers.Add(possibleNumbers(r)); 'Note that Im grabbing the value from possibleNumbers by its ordinal position 'remove the selected number so it cant be chosen again. possibleNumbers.Remove(r); 'Not that this will shorten the length of possibleNumbers, meaning that the next random we generate will still be within the size of the list }
There's probably bundles of errors in there but it should give a decent example of how to put items into and retrieve items from a List, with particular reference to the lottery problem. Of course, this is just one approach and there are others.
For a more generalised overview of the different types of collections (not Collections) I thought DDays FAQ was good and well worth a read. There's lots of different ones and they all apply in different circumstances so it's worth having the sort of high level overview he's given.
I hope that helps and I haven't taken your thread to far away from your intention.
Edit>Wow, the C# code highlight option in the forum is truly horrible.
Last edited by FunkyDexter; May 12th, 2016 at 08:56 AM.
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
May 12th, 2016, 10:40 AM
#23
Re: Trying to understand Collections
Dday9, I'm sorry I upset you, I really didn't mean to, I've always valued your advice.
I've looked again at #9, and I see where you answer my question... I didn't recognise it as the answer at the time I read it.
I'm being summoned by SWMBO at the moment so I can't try it out... I will.
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 12th, 2016, 10:42 AM
#24
Re: Trying to understand Collections
Poppa, I'm going over /just/ your posts in this thread, and you've never actually clearly stated the problem. I'm able to piece it together by reading between the lines, but it was very difficult. You said this at one point:
In this instance I've not posted any code, normally I would but I don't believe adding code would actually help here.
That was counterproductive. The working code with concatenation you showed was the first part of this whole sordid chain where I figured out what you were trying to do. I'm still not 100% sure I'm completely clear. But I'm going to move forward, with some stern words from time to time.
Let's lead with the stern part.
We have to be clear from the start: using a formatted string to store values is garbage. I'm presuming you came here because you agree, and want a better solution. I think there's probably already better solutions in this thread. But it feels like you strung several people I respect along and only revealed your real requirements after they'd already spent a collective man-day on trying to answer the questions you hadn't asked yet. That's made them a bit agitated. Next time, post your code first, so the forums can write solutions that provably do the same thing.
OK. Working solution time.
Don't get hung up on the words "key" and "value". You're working with a pair of items of arbitrary type. We have to call these pairs something. We can call them "one" and "two". We can call them "A" and "B". More meaningful names would be nice. But there's a lot of problems in computer science that use the phrase "key/value pair" or "name/value pair". We're used to using those words. The .NET Tuple class uses "Item1" and "Item2". Whatever. If I say "key" and "value", just mentally translate it to whatever you want to call your first item and second item, OK?
Solution 1: Make a Dang Class
VB .NET is an object-oriented language. Classes are how we associate related concepts with each other. There is a large portion of the community with the belief that creating classes is complicated, and programs with lots of classes are complicated, and people who make classes are trying too hard. These people are wrong. Large programs are complicated because they are large, not because of the practices used to create them. One cannot point at a 200-line program with two classes and compare it to a 100,000 line with 1,000 classes and claim the classes are why it's complex. The complexity comes from the 99,800 lines the 200-line program didnt' have to carry. This is another critical point. If you disagree, you're wasting your time reading my answers. You think I'm arrogant? Damn right. I don't get paid to be nice about programming, I get paid to be right. And I keep getting hired. So I'm either a skillful liar or a person worth listening to.
Maybe in some cases the pair is a first name and a last name. Maybe sometimes it's a name and a raffle ticket number. It doesn't matter. The unit that represents a "pair" can be a class:
Code:
Public Class Name
Public Property First As String
Public Property Last As String
End Class
Public Class RaffleEntry
Public Property Owner As Name
Public Property Number As Integer
End Class
If you squint, you could argue RaffleEntry is actually holding 3 values! Let's not think too hard about it.
You want a list of these? Make a list. No one uses Collection. I'm serious. And don't even think about ArrayList. If the year is 2003, that's fine. But it's 2016, and we've had 11 years to learn why Collection and ArrayList are bad ideas. If you want to argue with a million people, feel free. This isn't a mountain I'm dying on. (It's actually not even a mountain, it's more like a crater.)
Store:
Code:
Dim myName As New Name() { With .First = "Grayscale", .Last = "MountainDew" }
Dim anotherName As New Name() { With .First = "Nathaniel", .Last = "Reynolds" }
Dim names As New List(Of Name)()
names.Add(myName)
names.Add(anotherName)
Retrieve:
Code:
Dim theName As Name = names(0)
Dim firstName As String = theName.First
Dim lastName As String = theName.Last
Now, a Dictionary would help with faster lookups, but more and more I get the feeling you don't really care about fast lookups, you're more interested in iteration/indexing. There you go. Use a List of a Class type.
Solution 2: Use a Tuple
Fine. For some reason you hate using classes. If you want to pretend it's a lot easier to use a Tuple, I'm going to rewrite solution 1 using Tuples to show how funcitonally identical yet more cognitively challenging it is. Let's say a Name is a pair of Strings for first and last name.
Store:
Code:
Dim myName As New Tuple(Of String, String)("Grayscale", "Mountaindew")
Dim anotherName As Tuple(Of String, String)("Nathaniel", "Reynolds")
Dim names As New List(Of Tuple(Of String, Of String))()
names.Add(myName)
names.Add(anotherName)
Retrieve:
Code:
Dim theName As Name = names(0)
Dim firstName As String = theName.Item1
Dim lastName As String = theName.Item2
It's basically the same thing, that's the joke at the expense of people that insist it's SO complex to make a new class. I find it easier to remember "Name" consists of "First" and "Last". I don't find it easy to remember "Tuple(Of String, String).Item1 is a first name" and "Tuple(Of String, String).Item2 is a last name". I think a person who argues the overhead of a 4-line class ruins a program has never actually written a significant project. Strong opinion, I know.
But what really matters is understanding that in .NET, to represent 2 bits of data in a collection type, we have to create some other type that has the two bits of data. That means using a Class, or a Structure, or a Tuple. And when we choose that type, the best tools for keeping groups of those types around live in the System.Collections.Generic namespace. These are facts. Other solutions have to justify themselves with extensive technical analysis.
I can think of some sort of funny alternate solutions, but let's hold up. If neither of these solutions suits your fancy, what is it exactly that they are missing? Whatever requirement you have, the new feature will be built upon one of these two solutions. Post it all. At some point it's your job to add the features.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 13th, 2016, 04:41 AM
#25
Re: Trying to understand Collections
 Originally Posted by Sitten Spynne
Solution 1: Make a Dang Class
Maybe in some cases the pair is a first name and a last name. Maybe sometimes it's a name and a raffle ticket number. It doesn't matter. The unit that represents a "pair" can be a class:
Code:
Public Class Name
Public Property First As String
Public Property Last As String
End Class
Public Class RaffleEntry
Public Property Owner As Name
Public Property Number As Integer
End Class
If you squint, you could argue RaffleEntry is actually holding 3 values! Let's not think too hard about it.
You want a list of these? Make a list. No one uses Collection. I'm serious. And don't even think about ArrayList. If the year is 2003, that's fine. But it's 2016, and we've had 11 years to learn why Collection and ArrayList are bad ideas. If you want to argue with a million people, feel free. This isn't a mountain I'm dying on. (It's actually not even a mountain, it's more like a crater.)
Store:
Code:
Dim myName As New Name() { With .First = "Grayscale", .Last = "MountainDew" }
Dim anotherName As New Name() { With .First = "Nathaniel", .Last = "Reynolds" }
Dim names As New List(Of Name)()
names.Add(myName)
names.Add(anotherName)
Retrieve:
Code:
Dim theName As Name = names(0)
Dim firstName As String = theName.First
Dim lastName As String = theName.Last
Now, a Dictionary would help with faster lookups, but more and more I get the feeling you don't really care about fast lookups, you're more interested in iteration/indexing. There you go. Use a List of a Class type.
Thank you Sitten Spynne,
I managed to figure out how to get your Solution 1. to work.
It took a while to discover that 'With' should be before the {, but once that was sorted it all went like clockwork, Oh... I had to change Public Class Name to Public Class aName because Name apparently clashes with something else... But I get the fundamentals.
I'm going to try to get along with this new (to me) concept.
I am very grateful to all the guys trying to help, when I asked the original question I thought I'd get one or two replies with four or five lines explaining how the retrieve the data... now here we are at post #25!
Funky Dexter,
Oh, so it's not even your own problem you're trying to resolve. Yeah, I can see how going round the houses to try and solve someone else's problem could get kind of frustrating.
Well actually I was trying to incorporate what jmcilhinney said in that thread into an up-date of one of my very old programs. Now though, I'm going along with Sitten Spynne's solution.
Now I hope that this doesn't upset anyone, but I still can't see what's so very bad about the way I did it; it works, it's simple and I understood what I was doing... I learned BASIC when the B still stood for Beginner's !
At that tine I had various flavours of BASIC, the first, and the one I used most came on a 24 pin IC, and was I think produced by a company called OHIO in the USA. At that time there were programs such as G BASIC, Toshiba Basic, (for which I still have the manuals at home) and a few others who's names I don't recall, "Beginner's" was the key word because the language was much easier to get to grips with than (say) FORTRAN, COBOL, Lisp, Algol or (say) Pascal, all of which I had a crack at. By 1980, the year the Z80 was launched, I was programming in 6502 Machine Code until I found Assembly Language, which produced Machine Code more easily. i.e. faster.
Then in 1991, along came Microsoft with Visual Basic V3.0 which I used, that year, to control a very large industrial machinery complex via a 361 computer (381 ?, I forget) and several extension boards I designed and built for the IO. The machines themselves were run by their own control system using PLCs, for which I'd written the control program in their own programming language who's name I never heard. Not bad I'd say for an ex Royal Navy Aircraft maintenance fitter of 13+ years service some ten years prior.
Today I program (supposedly) for fun, and in the hope of keeping the grey cells working, so if I've seemed to disregard any of your suggestions I apologise.
Poppa.
PS, You can put the violins away now.
Pop.
Last edited by Poppa Mintin; May 13th, 2016 at 04:46 AM.
Along with the sunshine there has to be a little rain sometime.
-
May 13th, 2016, 05:23 AM
#26
Re: Trying to understand Collections
I still can't see what's so very bad about the way I did it
I don't think it's very bad. Ultimately it would work and, as long as you don't need pipes in the elements and you're not trying to eek every inch of performance out of this algorithm, I wouldn't call it "wrong".
I would call it imperfect though. It's limited because it doesn't allow pipes and it uses string parsing (which is processor hungry). The techniques given in this thread are "better" because they don't suffer from those two issues. Notably, none of them are perfect either - because perfect doesn't exist outside of pure maths.
I guess I'm saying, our job is primarily to make something work. But it's also, secondarily, to make something work better.
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
May 13th, 2016, 09:05 AM
#27
Re: Trying to understand Collections
 Originally Posted by Poppa Mintin
I am very grateful to all the guys trying to help, when I asked the original question I thought I'd get one or two replies with four or five lines explaining how the retrieve the data... now here we are at post #25!
To show how our solutions worked we had to create some data to go along with our answers, so a few lines was out of the question.
-
May 13th, 2016, 10:14 AM
#28
Re: Trying to understand Collections
It took a while to discover that 'With' should be before the {, but once that was sorted it all went like clockwork, Oh... I had to change Public Class Name to Public Class aName because Name apparently clashes with something else... But I get the fundamentals.
Whoops. True story: I work on a Mac OS machine and it's a little difficult for me to get to my Windows box. VS 2015 takes 10 minutes to boot on it. So for simple code examples, I tend to just freehand type into a text editor and hope the reader can handle any simple syntax mistakes I make. This is also a bit hindered by I haven't written VB .NET at a job since... well, 2004, so some of the nuances aren't muscle memory.
Anyway, I also want to comment on:
I still can't see what's so very bad about the way I did it
You need to know this. It's fundamental to how the machine you're operating works. A lot of people say they want to program but not care about what's going on inside the machine. This is sort of dangerous. Computers, when you're programming, are heavy machinery. Operating a dump truck requires more intimate knowledge of how the machine operates than operating your average car. Computers, when driven by a programmer, are much more like dump trucks than shiny, self-driving Teslas. It's our job to make the dump truck look like a Tesla. We're illusionists. Let's pull back the curtain.
Data has to get stored in memory somehow. Doubles take up 64 bits. Integers take up 32 bits. Strings... can be represented many ways. .NET happens to represent them as UTF-16 encoded character arrays, which means every String is at least 2 bytes per character plus a teeny bit of overhead for the array. Strings are also immutable, which means .NET doesn't let you update a String's memory in place. If you change just one letter, it creates a new array, copies the old values in, and adds the new value.
So if you join the two strings "as" and "df" with .NET, first a 4-byte array is created for "as", then a 4-byte array is created for "df", then a new 8-byte array is created, and "as" then "df" is copied into that 8-byte array. It takes 16 bytes of memory and 3 copy operations. You don't even notice, but this is a cost.
So string storage of most data is not as efficient as leaving it in its native type. The integer 123 uses 4 bytes. The String "123" uses 6. The Double 1.2345 uses 8 bytes. The string uses 16 bytes or more, depending on how you truncate the number. But we're not done.
If an integer is an integer, there's no work involved with using it as a number. If an integer is a string-encoded number, it takes work to parse it. How much work? Well, the basic algorithm involves checking each digit, a multiplication for the power of ten, and an addition. So for every digit in the number, we need to take 3 steps. It takes 1 'step' to evaluate the Integer 1234. It takes 12 'steps' to convert the string "1234" into the integer. The more digits in the data value, the worse this gets, but the best-case is one digit, where it still takes 3 steps.
So let's put it all together. What's it cost to store the name "John Smith" and his database ID 12345 in the string "John Smith|12345" vs. in a class? What's it cost to separate the values?
For the class, we're consuming 20 bytes worth of String and 4 bytes of integer. Accessing either takes 1 'step'. So 24 bytes and 2 steps.
For the string, we're consuming 32 bytes worth of String. In order to separate the values we have choices. Suppose we use Split():
- Split() has to iterate the string to find the index of each '|', then make a break. So that's 16 steps for iteration, and it has to create 20 bytes of String for the name and 10 bytes worth of String for the integer.
- Getting the string is one step.
- Getting the integer uses parsing, so we have to allocate 4 bytes for the Integer and perform 15 steps for the parsing.
For the string, we're using 32 bytes initially. To get the two values consumes another 34 bytes and takes 32 steps.
The 64 bytes the String uses is 3x what the class uses, and can get even worse. The 32 steps it uses are 16x the 2 steps the class uses, and can get even worse. Those steps translate to CPU cycles, which waste both your user's time and battery. That's why I say it's bad.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 13th, 2016, 10:58 AM
#29
Re: Trying to understand Collections
It feels like the OP is not really asking for an answer but validation that his horrible solution is OK. Just give him that.
Use a pipe divider Poppa, its OK.
More important than the will to succeed, is the will to prepare for success.
Please rate the posts, your comments are the fuel to keep helping people
-
May 13th, 2016, 12:32 PM
#30
Re: Trying to understand Collections
I'd like to give Poppa the benefit of the doubt, and not use my position as a very experienced .NET developer to make him feel small or stupid.
It is very possible to spend an entire career in the absence of a mentor, and not learn some very fundamental Computer Science topics. I was blessed. I started reading them in math books in elementary school. I was able to afford a formal education. I was passionate enough to read between the lines, if I'd have just read my lecture notes I'd be a quarter of the developer I am today. I spent a lot of money and time devouring books I didn't need to read. I try to spend time every day talking to people smarter than me.
I like to be that mentor to other people. I can't get there if I belittle them. People helped me get where I am. I feel obligated to help others get there too.
I want to remember this post as something I hope I never say about another person to their face again. I want Poppa to feel smart and big. Not dumb and small. We can't get there if I patronize him. He might still disagree with me. That's fine. I've been posting on programming forums for 10 years. If that happens, he'll be back later, with a problem he can't solve with formatted strings. And then he'll be enlightened. Or he won't. I choose to spend my time here, and he's not the only person reading the thread.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 14th, 2016, 03:09 AM
#31
Re: Trying to understand Collections
 Originally Posted by FunkyDexter
I guess I'm saying, our job is primarily to make something work. But it's also, secondarily, to make something work better.
Thanks FunkyDexter,
If I were working on something I proposed to publish I would have to take all that into consideration,
as it happens I program for fun, and the little applications I embark upon are mostly for my own use,
a few find their way onto my wife's computer, and one or two even find their way onto my son's.
dbasnett
To show how our solutions worked we had to create some data to go along with our answers, so a few lines was out of the question.
Thanks Dbasnett, I understand that, I just didn't expect it.
Sitten Spynne
In order to separate the values we have choices. Suppose we use Split():
Split() has to iterate the string to find the index of each '|', then make a break. So that's 16 steps for iteration, and it has to create 20 bytes of String for the name and 10 bytes worth of String for the integer.
Getting the string is one step.
Getting the integer uses parsing, so we have to allocate 4 bytes for the Integer and perform 15 steps for the parsing.
For the string, we're using 32 bytes initially. To get the two values consumes another 34 bytes and takes 32 steps.
The 64 bytes the String uses is 3x what the class uses, and can get even worse. The 32 steps it uses are 16x the 2 steps the class uses, and can get even worse. Those steps translate to CPU cycles, which waste both your user's time and battery. That's why I say it's bad.
Thanks Sitten Spynne,
That's certainly an eye-opener.
"Suppose we use Split():"
Out of curiosity, and since the first element is always an integer, suppose we use: -
Code:
Sub Get_em(ByVal WrdIn As String)
Dim Num As Integer, Wrd As String
Num = Val(WrdIn)
Wrd = WrdIn.Substring(InStr("|"))
End Sub.
(yeah I know it doesn't go anywhere)
Would that cost us more or less ?
(If you have the time to think about it)
kaliman
It feels like the OP is not really asking for an answer but validation that his horrible solution is OK. Just give him that.
Use a pipe divider Poppa, its OK.
Thanks for the kind thought Kaliman, nice of you.
(OP = Old Person ?)
Sitten Spynne
I want to remember this post as something I hope I never say about another person to their face again. I want Poppa to feel smart and big. Not dumb and small. We can't get there if I patronize him. He might still disagree with me. That's fine. I've been posting on programming forums for 10 years. If that happens, he'll be back later, with a problem he can't solve with formatted strings. And then he'll be enlightened. Or he won't. I choose to spend my time here, and he's not the only person reading the thread.
Thanks again Sitten Spynne,
When I'm bored and need something interesting to do, I usually open VB Forums.
(It's my belief that this forum used to be called 'VB Wire' ?)
I take a look at all the unanswered threads, if I think I can suggest something, I 'take my ass in my hand' and give it a shot...
If subsequently my suggestion gets shot down, well at least there's been at least one proposed solution, if it means they're able to continue with their project until something better comes along, all well and good. After all, surely a working answer is better than no answer at all.
Thank you all for your time and patience...
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 14th, 2016, 05:48 AM
#32
Re: Trying to understand Collections
OP = original poster - he who started the thread.
-
May 14th, 2016, 07:15 AM
#33
Re: Trying to understand Collections
 Originally Posted by szlamany
OP = original poster - he who started the thread.
Yeah... 
Pop.
Along with the sunshine there has to be a little rain sometime.
-
May 14th, 2016, 10:03 AM
#34
Re: Trying to understand Collections
Out of curiosity, and since the first element is always an integer, suppose we use: -
Code:
Sub Get_em(ByVal WrdIn As String)
Dim Num As Integer, Wrd As String
Num = Val(WrdIn)
Wrd = WrdIn.Substring(InStr("|"))
End Sub
(yeah I know it doesn't go anywhere)
Would that cost us more or less ?
(If you have the time to think about it)
Think it through. Val() can't be doing anything more magic than Integer.Parse(). Its behavior is:
Code:
* Ignore whitespace characters.
* When a digit is found, start looking for a non-digit.
* Do the standard integer parse algorithm on the digits.
Let's use the input string "12345|John Smith", because my original sample string would fail your algorithm 
- Val() is going to have to iterate past "12345" until it reaches |. 6 steps.
- Then it has to read backwards to perform integer parsing, 3 steps per digit. 15 steps.
- And we've also had to allocate an Integer, 4 bytes.
After that, InStr() has to resolve. It has to start at the front and iterate to the "|", which is 6 steps. 12 if we count the comparison, but we haven't so far so let's not start.
It allocates the integer 5 as its return value. (Technically this is then copied onto the parameter stack but I haven't been paying attention to that either.) 4 more bytes.
Now an array with 10 elements is allocated (20 bytes), and 10 iterations happen to copy it. (10 steps)
So we weigh in at 6 + 15 + 6 + 10 = 37 steps, and 4 + 4 + 20 = 28 bytes. That's closer to the 24 bytes the class took, but 37 steps compared to 2 is a lot of wasted time.
Due to the immutability of strings, and the iterative nature of parsing values, the only way I can imagine string storage being as time efficient is "I want to store 10 1-digit Integers in a 10-character string." Though one might point out you can pack a 1-digit integer into a 3-bit number, so the 10 numbers would be 30 bits (4 bytes with 2 unused bits). The string would be 20 bytes. You can't win, with conversions.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 14th, 2016, 12:41 PM
#35
Re: Trying to understand Collections
 Originally Posted by Sitten Spynne
Think it through. Val() can't be doing anything more magic than Integer.Parse(). Its behavior is:
Code:
* Ignore whitespace characters.
* When a digit is found, start looking for a non-digit.
* Do the standard integer parse algorithm on the digits.
Let's use the input string "12345|John Smith", because my original sample string would fail your algorithm
- Val() is going to have to iterate past "12345" until it reaches |. 6 steps.
- Then it has to read backwards to perform integer parsing, 3 steps per digit. 15 steps.
- And we've also had to allocate an Integer, 4 bytes.
After that, InStr() has to resolve. It has to start at the front and iterate to the "|", which is 6 steps. 12 if we count the comparison, but we haven't so far so let's not start.
It allocates the integer 5 as its return value. (Technically this is then copied onto the parameter stack but I haven't been paying attention to that either.) 4 more bytes.
Now an array with 10 elements is allocated (20 bytes), and 10 iterations happen to copy it. (10 steps)
So we weigh in at 6 + 15 + 6 + 10 = 37 steps, and 4 + 4 + 20 = 28 bytes. That's closer to the 24 bytes the class took, but 37 steps compared to 2 is a lot of wasted time.
Due to the immutability of strings, and the iterative nature of parsing values, the only way I can imagine string storage being as time efficient is "I want to store 10 1-digit Integers in a 10-character string." Though one might point out you can pack a 1-digit integer into a 3-bit number, so the 10 numbers would be 30 bits (4 bytes with 2 unused bits). The string would be 20 bytes. You can't win, with conversions.
Wow... Complicated ain't it !
Thanks for the time and effort, complicated, but interesting.
Poppa.
Along with the sunshine there has to be a little rain sometime.
-
May 14th, 2016, 10:16 PM
#36
Re: Trying to understand Collections
Long story short - ANY string manipulation is always going to be more complicated and time consuming than pretty much any other option. And just think, in this case it's only two data points.... expand it out to another 4 or 5, and then introduce addresses, phone numbers, weight, eye color.... you can see it gets even more complicated...
-tg
-
May 15th, 2016, 05:28 AM
#37
Re: Trying to understand Collections
 Originally Posted by techgnome
Long story short - ANY string manipulation is always going to be more complicated and time consuming than pretty much any other option.
-tg
Yeah, I guess the point has been made often enough even for me to get it. 
In the particular application that started this whole thread off though...
The data starts off as a string read in from a text file, each string consists of a date, a message, and optionally a command to advance the date, on a given day (Yesterday) to a date foretold by the optional command, which incidentally consists of an integer, saying how many, and a code for: Day, Week, Month or Year... Or an integer giving an ordinal number, i.e. 1st, 2nd, 3rd, 4th or (with no number at all) Last: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday or Saturday of either this month or, depending on today's date, next month.
This text file is edited via the application and added to or edited via a separate application which, when these two applications were first written in the middle 1990s, was the easiest way for me to do it.
Poppa.
Last edited by Poppa Mintin; May 15th, 2016 at 05:31 AM.
Reason: insert ommission
Along with the sunshine there has to be a little rain sometime.
-
May 15th, 2016, 08:53 AM
#38
Re: Trying to understand Collections
Yes, OK, this is a good place to add some data to what seems to be a condemnation of string types for storage at all.
If we want the smallest possible file size, and the fastest possible read times, then binary files are the way to go. But debugging them is a nightmare, and when I write binary files I also always end up having to write tools to help me visualize them.
Text files are larger, but I can read them. And I can hand-edit them. And sometimes, if they get corrupted, I have half a chance of fixing them. This is why, even though they're obsessed with doing arcane things in the name of performance, UNIX developers standardized on 'simple' text formats for all of their tools. Heck, even HTTP uses text even though, at the time it was created, the data rates actually made sending text files take time! It's just so much more valuable to SEE your data.
So if you're writing to a file, or reading from a file, that is a fine time to have a string that represents a more complicated object. Don't keep that string around, though. If you read a line, and you're going to need to manipulate the data it represents, it's almost always wiser to convert the entire string into an object, manipulate the object, then convert it back to a string. We can sometimes figure out what we're doing is more efficient if we leave the string alone. Those cases only present themselves after 10+ minutes of careful analysis. And they save us milliseconds per year. So they're regularly moot.
So my rule of thumb is if I have a formatted string, I want to convert it to an object ASAP. And if an object is bound for a file, I want to convert it to a String representation somehow. CSV-style is great. JSON is great. I'm getting tired of XML at this point. It takes 50 lines of code and 100 extra characters to say something in XML compared to everything else. It's all-around easier for me to read CSV and JSON. And that's why I picked text in the first place, so I could read it!
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
-
May 15th, 2016, 02:50 PM
#39
Re: Trying to understand Collections
 Originally Posted by Sitten Spynne
Yes, OK, this is a good place to add some data to what seems to be a condemnation of string types for storage at all.
So my rule of thumb is if I have a formatted string, I want to convert it to an object ASAP. And if an object is bound for a file, I want to convert it to a String representation somehow. CSV-style is great. JSON is great. I'm getting tired of XML at this point. It takes 50 lines of code and 100 extra characters to say something in XML compared to everything else. It's all-around easier for me to read CSV and JSON. And that's why I picked text in the first place, so I could read it!
Thanks Sitten Spynne,
I had to 'Google' CSV and JSON. 
I've seen both but not recognise 'em under those names.
CSV looks easy... JSON looks like C to me. (But I gave up C several years ago... Well, C++ actually) "You can't teach an old dog new tricks" (Not even an old Sea Dog).
I too like the fact that I can just open my files with NotePad and fix any problems which may've occurred. Then I have to dive in to see what caused the error, fortunately that's not happened for many years now.
I may well take a look at using CSV, I can see that it's pretty versatile. P'raps not for this current App. but I may devise something to test it out with.
My current program has worked well enough for a long while now and it's going to take me a good while to convert from invisible ListBoxes to Classes but I shall persevere, it'll keep me busy for a good while.
My guess is, that at the end of it all I'll not notice any difference in speed, nor will it matter... The App. opens, I read the first message, I click a button... Read the next message... Click the button, and so on until the list is empty, I usually accept the invitation to see what messages have been deleted (because they're out of date), but I don't have to, I can opt to edit or add to the existing messages if I wish, or just close the App.
The App. is in my 'startup' page, so it automatically opens when I start the computer, I can of course open it with a link on the desktop should I wish.
Poppa.
PS. This must be a form of CSV...
Code:
Dim Txt() As String = {"dummy", "Select", "Restore", "Start", "Pause", "Stop",
"Next", "Done", "Plus", "Minus", "Set This Interval", "Remove", "Exit"}
... surly ?
Pop.
Last edited by Poppa Mintin; May 15th, 2016 at 02:59 PM.
Reason: PS Added.
Along with the sunshine there has to be a little rain sometime.
-
May 15th, 2016, 03:00 PM
#40
Re: Trying to understand Collections
Ahh yes. The innate fear of brackets so characteristic of the VB developer. It's one of the few things I WILL poke fun at. I don't believe in "That looks like C, I'm ignoring it". It's a good way to drown. Here's the way it breaks down.
In terms of text formats, MS bet on XML very hard. They did this because they spent a lot of money on tools that worked with a very complex XML-based network programming protocol called "SOAP". It stood for "Simple Object Access Protocol". It was so simple, anyone who could write functioning SOAP code without using some GUI to generate it should be suspected of witchcraft and burned. It's almost impossible to use it without Visual Studio or some other expensive tool managing all the magic for you. Can you imagine why MS might've made such a hard bet on XML?
CSV has been around forever, and doesn't have to use commas. When you were using pipe-delimited strings, you were using a CSV format. It's just "one 'row' of data per line, each 'column' separated by some character". The end. Super simple. Most languages have a CSV parser. Microsoft hid VB's way out in a library they don't include by default, and C# has to use the VB one. Most .NET developers don't even know it's there, because MS puts XML front and center.
Everyone else in the world looked at this and shook their head. The whole reason for using text is so you can debug your protocol easily. Making it so complex you need expensive tools to generate the code goes against that. They noticed JavaScript had a pretty simple object notation. Got an object with a FirstName and LastName property? It serializes to "{FirstName: "Sitten", LastName: "Spynne"}". Easy peasy. There's a parser in every language, and they built a competitor to SOAP called REST off of it. REST is super easy. You can literally write a REST server in 10-15 lines of VB .NET. You're lucky if you can get a SOAP application working with less than a few hundred.
.NET doesn't have any readily-accessible JSON parsers, because MS spent all that money on XML and wants you to believe that <> is easier to read than {}. There is ONE JSON parser in the BCL you can use by including some web libraries, but it's not 100% compatible with how the rest of the world speaks JSON in some weird, subtle ways. So you have to use a third-party JSON parser, and the Netwonsoft one's really good. JSON's what I use if I've got to make stuff that's parsed by both .NET and some other language. XML's what I use if I'm getting paid hourly. I'll use CSV if I've got some reason to not use JSON, but I really like JSON.
That's not the be-all end-all though. Some other formats like INI exist. They have [Sections] and use name=value pairs under those sections. A lot of UNIX config files just use name=value pairs. That looks sort of like CSV, but it can only do one bit of data per line where CSV attempts to fit lots of data per line. .NET doesn't have parsers for these kinds of formats, but it takes less than ten minutes to write one so that's no big deal.
In short, just steer clear of XML. .NET has the best XML parsers in the world. But it's sort of like having the best asbestos insulation in the world.
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
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
|