Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: .NET VB.NET
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!
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 28-Aug-14 5:32am
Edited 28-Aug-14 7:07am
Nelek60.2K
v3

1 solution

Rate this: bad
good
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
Else
    Return 0
End If
  Permalink  
Comments
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).
—SA
Sergey Alexandrovich Kryukov at 28-Aug-14 18:07pm
   
Sure, makes full sense, a 5.
—SA
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 OriginalGriff 304
1 Sergey Alexandrovich Kryukov 295
2 Shweta N Mishra 216
3 Maciej Los 210
4 PIEBALDconsult 184
0 OriginalGriff 7,630
1 Sergey Alexandrovich Kryukov 7,022
2 DamithSL 5,586
3 Manas Bhardwaj 4,946
4 Maciej Los 4,525


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