C# - How do I order a list of colors in the order of a rainbow?

Viewed 848

From a list of images, I calculated the average color using a method similar to this. I now have a list of System.Drawing.Color, but I'm not sure how to sort them in a way that it looks like a rainbow.

Here is something simple I have tried (slightly changed for example purposes):

var colorList = new List<Color>
{
    Color.Red,
    Color.Purple,
    Color.Black,
    Color.Blue,
    Color.Green,
    Color.LightGreen,
    Color.LightSkyBlue,
    Color.Yellow
};

var orderedColorList =
    colorList.OrderBy(o => (o.R * 3 + o.G * 2 + o.B * 1));

This does not seem to create a rainbow but more of an effect from black to white.

How would I be able to sort them in a way that results in a rainbow?

1 Answers

If you order by the Hue first, and then RGB, you should get a rainbow ordering:

var orderedColorList = colorList
    .OrderBy(color => color.GetHue())
    .ThenBy(o => o.R * 3 + o.G * 2 + o.B * 1);

Using a mixed-up collection of rainbow colors, this appears to do the trick:

var colorList = new List<Color>
{
    Color.LightSkyBlue,
    Color.Red,
    Color.Yellow,
    Color.Purple,
    Color.Orange,
    Color.Blue,
    Color.Green
};

var orderedColorList = colorList
    .OrderBy(color => color.GetHue())
    .ThenBy(o => o.R * 3 + o.G * 2 + o.B * 1);

foreach (var color in orderedColorList)
{
    Console.WriteLine(color.Name);
}

Output

enter image description here

Related