timberman17
timberman17

Reputation: 1

VB - Count of Each Number in a File

​I'm trying to write code that will read a text file of numbers similar to this

 1234
 5678
 0123     

and count the total times each number is repeated in the file

I can open the file and parse the contents to a list box but I don't know how to count the total number of times each 0-9 appears in the entire file.

I was hoping that someone could tell me in theory, how to attack this.

I'm a relative beginner with VB using Visual Studio 2012. I'm not a student.

Thanks in Advance !!!

Upvotes: 0

Views: 49

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use LINQ's GroupBy to create a Dictionary(Of String, Int32):

Dim numberCounts As Dictionary(Of String, Int32) = File.ReadLines("Path").
     GroupBy(Function(line) line.Trim()).
     ToDictionary(Function(group) group.Key, Function(group) group.Count())

So each dictionary key is a (unique) number in the file and the value is it's count.

If you instead want to know the number each digit(0-9) is contained in the file:

Dim digitCounts As Dictionary(Of Char, Int32) = File.ReadLines("Path").
     SelectMany(Function(line) line.Where(AddressOf Char.IsDigit)).
     GroupBy(Function(digitChar) digitChar).
     ToDictionary(Function(group) group.Key, Function(group) group.Count())

Upvotes: 1

Nick Bailey
Nick Bailey

Reputation: 3162

First, parsing the data to a listbox is not advisable. You should not use user interface elements to store data. User interface elements are for displaying data and accepting input from the user. Never use them for anything else. By separating concerns, you make your application easier to debug, easier to understand and easier to modify (imagine you want to completely change the interface so it doesn't use listboxes... kinda hard to do if that's how you're doing data storage).

Second, the tool you are looking for is the Dictionary class in the system.collections.generic namespace. Try reading the description of the class and see if you can figure out how you can use it to solve the problem. Post some code if you can't get that to work.

Upvotes: 0

Related Questions