A Simple LINQ Example with System.Reflection and System.Drawing.Color
Recently I needed to get see all the RGB values for the System.Drawing.Color values (for example System.Drawing.Color.Red, System.Drawing.Color.Aqua, etc.).
It's a very simple task that shows some of the expressive simplicity of LINQ.
Here's the sample using the LINQ method syntax:
using System;
using System.Linq;
namespace CmdLineTest
{
internal class Program
{
[STAThread]
private static void Main(string[] args)
{
var color_type = typeof(System.Drawing.Color);
var color_properties = color_type.GetProperties()
.Where(m => m.PropertyType == color_type );
foreach (var color_property in color_properties)
{
var cur_color = (System.Drawing.Color)color_property.GetValue(null, null);
uint rgb_int = (uint)cur_color.ToArgb() & (0x00ffffff);
Console.WriteLine(" {0} = ({1},{2},{3}) = 0x{4:X00000000}",
color_property.Name,
cur_color.R, cur_color.G, cur_color.B,
rgb_int );
}
}
}
}
Here's the sample using the LINQ query syntax:
using System;
using System.Linq;
namespace CmdLineTest
{
internal class Program
{
[STAThread]
private static void Main(string[] args)
{
var color_type = typeof(System.Drawing.Color);
var color_properties = from prop in color_type.GetProperties()
where prop.PropertyType == color_type
select prop;
foreach (var color_property in color_properties)
{
var cur_color = (System.Drawing.Color)color_property.GetValue(null, null);
uint rgb_int = (uint)cur_color.ToArgb() & (0x00ffffff);
Console.WriteLine(" {0} = ({1},{2},{3}) = 0x{4:X00000000}",
color_property.Name,
cur_color.R, cur_color.G, cur_color.B,
rgb_int );
}
}
}
}
The output will look like this
Transparent = (255,255,255) = 0xFFFFFF
AliceBlue = (240,248,255) = 0xF0F8FF
AntiqueWhite = (250,235,215) = 0xFAEBD7
Aqua = (0,255,255) = 0xFFFF
Aquamarine = (127,255,212) = 0x7FFFD4
Azure = (240,255,255) = 0xF0FFFF
Beige = (245,245,220) = 0xF5F5DC
Bisque = (255,228,196) = 0xFFE4C4
Black = (0,0,0) = 0x0
BlanchedAlmond = (255,235,205) = 0xFFEBCD
Blue = (0,0,255) = 0xFF
BlueViolet = (138,43,226) = 0x8A2BE2
Brown = (165,42,42) = 0xA52A2A
BurlyWood = (222,184,135) = 0xDEB887
CadetBlue = (95,158,160) = 0x5F9EA0
Chartreuse = (127,255,0) = 0x7FFF00
For the record: my favorite is System.Drawing.Color.Tomato