Home » Programming » C# » The fastest algorithm in C#/VB.Net to count how many times a value is repeated in a List of items

The fastest algorithm in C#/VB.Net to count how many times a value is repeated in a List of items

posted in: C#, Programming, VB.Net 0

The faster way (with the best system performance) to count how many times a particular value is repeated in a List of items, it’s like this

[sourcecode language=”vb”] Const chars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Dim rnd As New Random()

‘create a long list of random letters
Dim random_letters As List(Of String) = Enumerable.Range(1, 100000).Select(Function(i) chars(rnd.Next(0, chars.Length)).ToString).ToList

‘create a long list of random numbers
Dim random_numbers As List(Of Integer) = Enumerable.Range(1, 100000).Select(Function(i) rnd.Next(100000)).ToList()


‘get a lookup table
Dim lookup_table = random_letters.GetLookupTable

‘count how many times a particular value "B" is repeated in the lookup table of random_letters List
Dim count As Integer = lookup_table.CountValue("B")
[/sourcecode]

To do that, You have to add the following two extension methods, optimized for the best performance, to my .Net module (at http://www.maxvergelli.com/useful-extension-methods-for-string-net-class-with-support-of-intellisense/) that extends the String class

[sourcecode language=”vb”] ‘CountValue() count how many times a particular value is repeated in a lookup table

_
Public Function CountValue(Of T)(ByRef lookup_table As Dictionary(Of T, Int32), ByRef value As T) As Integer
Dim c As Integer = 0
lookup_table.TryGetValue(value, c)
Return c
End Function

‘get a lookup table from a List of items

_
Public Function GetLookupTable(Of T)(ByRef list As List(Of T)) As Dictionary(Of T, Int32)
Dim table As New Dictionary(Of T, Integer)
For Each s As T In list
Dim count As Int32 = 0
If table.TryGetValue(s, count) Then
table(s) = count + 1
Else
table(s) = 1
End If
Next
Return table
End Function
[/sourcecode]

Enjoy,
Max 🙂


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.