Click here to Skip to main content
11,798,039 members (78,687 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: .NET VB.NET

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
Edited 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 at 28-Aug-14 13:29pm
Fantastic Richard!

It worked first time and is MUCH faster.

Many thanks for your help!!!
Sergey Alexandrovich Kryukov at 28-Aug-14 18:06pm
It's O(1).
Sergey Alexandrovich Kryukov at 28-Aug-14 18:07pm
Sure, makes full sense, a 5.
Philippe Mori at 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
0 CPallini 575
1 Maciej Los 375
2 OriginalGriff 353
3 Abhinav S 342
4 Richard MacCutchan 218
0 OriginalGriff 2,150
1 Maciej Los 1,790
2 KrunalRohit 1,456
3 CPallini 1,415
4 Richard MacCutchan 1,016

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 28 Aug 2014
Copyright © CodeProject, 1999-2015
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