Click here to Skip to main content
13,090,678 members (50,130 online)
Rate this:
Please Sign up or sign in to vote.
See more:

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!
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
Return 0
End If
Posted 28-Aug-14 4:32am
Updated 28-Aug-14 6:07am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try using a Dictionary keyed on the Color, where the value is either the MyColor class or just the ID value.
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
    Return 0
End If
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).
Sergey Alexandrovich Kryukov 28-Aug-14 18:07pm
Sure, makes full sense, a 5.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170813.1 | Last Updated 28 Aug 2014
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100