Matt Leyland
Matt Leyland

Reputation: 2329

Count re-Occurrence of a string - VB.NET

What method is best to count the following, Each line is a string created by a loop.

Jane
Jane
Matt
Matt
Matt
Matt
Jane
Paul

In the end i would like to know : Jane = 3, Matt = 4, Paul = 1. Would i use an array or a loop ?

Upvotes: 1

Views: 662

Answers (1)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

You can create a List(Of String) e.g.

Dim arr As New List(Of String)

And inside of your loop collect your strings:

arr.Add(CurrentString)

After the loop arr would have all the strings. Then you can run a simple LINQ query:

Dim Summary = From a In arr Group By Name = a Into Group _
              Select Name, Cnt = Group.Count()

This Summary will give you the counts. You can use it for example

For Each elem In Summary
    'Output elem.Name
    'Output elem.Cnt 
Next

For your example this will produce

Name = "Jane", Cnt = 3 
Name = "Matt", Cnt = 4
Name = "Paul", Cnt = 1

Upvotes: 2

Related Questions