Search code examples
c#datatablesystem.data

How to execute Datatable.Select() query for a column of type System.Color?


I have a DataTable where one of the columns is of type System.Color and whenever I need to query some rows according by color value I can't find the right syntax for that.

I need a solution which looks something like:

DataRow[] _queried = dataTable.Select("ColorColumn = " + System.Color.Red);

I have tried as string and int and didn't find a working solution.


Solution

  • DataTable.Select supports column expressions syntax, including CONVERT function. As it turns out, CONVERT works for columns of type System.Drawing.Color as well.

    Something like this should work:

    DataRow[] queried = table.Select("CONVERT(ColorColumn, System.String) = 'Color [Red]'");
    

    or, if you want to pass Color as a variable:

    var filterColor = Color.Red;
    var queried = table.Select($"CONVERT(ColorColumn, System.String) = '{filterColor}'");
    

    Runnable example:

    using System;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    
    class Program
    {
        private static void Main()
        {
            var table = new DataTable();
            table.Columns.Add(new DataColumn("Name", typeof(string)));
            table.Columns.Add(new DataColumn("Color", typeof(Color)));
            table.Rows.Add("First", Color.Red);
            table.Rows.Add("Second", Color.DarkRed);
            table.Rows.Add("Third", Color.Green);
            table.Rows.Add("Fourth", Color.Red);
            table.Rows.Add("Fifth", Color.Yellow);
            var filterColor = Color.Red;
            var queried = table.Select($"CONVERT(Color, System.String) = '{filterColor}'");
            //First, Fourth
            Console.WriteLine(string.Join(",", queried.Select(r => r["Name"])));
            Console.Read();
        }
    }