Click here to Skip to main content
15,860,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to find a quicker way to search through a large number of colors and get their associated ID values. Generally the code is listed below and it works fine but is unfortunately quite slow. I guess I need to sort the list somehow first and then search it (.NET binarysearch?)

Does anyone have any suggestions please?

Many thanks for any assistance!
VB
Public Class MyColor
    Public Property ID As Integer
    Public Property RGB As Color
End Class

'  Large amount of colors added to a list:
Dim allMyColors As List(Of MyColor) = New List(Of MyColor)

' Then with a known R,G and B value I search to see if it exists and get the associated ID value

Dim mc As MyColor = allMyColors.FirstOrDefault(Function(colorage) colorage.RGB.R = R And colorage.RGB.G = G And colorage.RGB.B = B)

If mc IsNot Nothing Then
Return mc.ID
Else
Return 0
End If
Posted
Updated 28-Aug-14 6:07am
v3

1 solution

Try using a Dictionary keyed on the Color, where the value is either the MyColor class or just the ID value.
VB.NET
Dim allMyColors As Dictionary(Of Color, Integer) = New Dictionary(Of Color, Integer)()
...
Dim id As Integer
Dim key As Color = Color.FromArgb(R, G, B)
If allMyColors.TryGetValue(key, id) Then
    Return id
Else
    Return 0
End If
 
Share this answer
 
Comments
codetowns 28-Aug-14 13:29pm    
Fantastic Richard!

It worked first time and is MUCH faster.

Many thanks for your help!!!
Sergey Alexandrovich Kryukov 28-Aug-14 18:06pm    
It's O(1).
—SA
Sergey Alexandrovich Kryukov 28-Aug-14 18:07pm    
Sure, makes full sense, a 5.
—SA
Philippe Mori 28-Aug-14 21:38pm    
By the way, last 5 lines can be replaced by: allMyColors.TryGetValue(key, id) and Return id since id will be 0 when not found.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900