In this Programming Post, we will see an example program to get string of comma separated values from DataTable Column in C#.Net.

Generally while working with DataTable, we may need to generate a comma (or any delimiter) separated string and even we may need to generate comma separated values with single quotes to use the string in any sort of Data Filter or to pass it for sql query IN or NOT IN clause etc,. We will achieve this in the following program.

Program :

using System;
using System.Linq;
using System.Data;

namespace DataTableColumnCommaSeperated
    class Program
        static void Main(string[] args)
            //Printing Dictionary
            Console.WriteLine("\n*** ***\n");
            Console.WriteLine("\n>>> C# Program to Get Comma Separated String from DataTable Column Values <<<\n");

            DataTable dt = getDepartments();

            //Generating string array from DataTable Column DeptId
            string[] strArr = dt.AsEnumerable().Select(r => Convert.ToString(r["DeptId"])).ToArray();

            //Generating CommaSeperated string from String Array
            string strCommaSeperated = string.Join(",", strArr);

            //Generating CommaSeperated string with single quoted values from String Array
            string strCommaSeperatedWithSingleQuotes = string.Join(",", strArr.Select(r => "'" + r + "'"));

            Console.WriteLine("Printing Comma Seperated String ");

            Console.WriteLine("Printing Comma Seperated String with single quoted values");


        /// <summary>
        /// returns sample DataTable
        /// </summary>
        /// <returns></returns>
        private static DataTable getDepartments()
            DataTable dtDept = new DataTable();
            dtDept.Columns.Add("DeptId", typeof(Int32));
            dtDept.Columns.Add("DeptName", typeof(String));
            dtDept.Columns.Add("DeptEmpCount", typeof(Int32));
            DataRow dr;

            for (int i = 1; i <= 5; i++)
                dr = dtDept.NewRow();
                dr["DeptId"] = i;
                dr["DeptName"] = "Dept" + i.ToString();
                dr["DeptEmpCount"] = (i * 10);
            return dtDept;



output text :

*** ***

>>> C# Program to Get Comma Separated String from DataTable Column Values <<<

Printing Comma Seperated String
Printing Comma Seperated String with single quoted values

Leave a Reply

Your email address will not be published. Required fields are marked *