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*** www.programmingposts.com ***\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(strCommaSeperated);

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

            Console.ReadLine();
        }

        /// <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);
                dtDept.Rows.Add(dr);
            }
            return dtDept;
        }
    }
}

Output:

comma-seperated-string-datatable-column-output

output text :

*** www.programmingposts.com ***

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

Printing Comma Seperated String
1,2,3,4,5
Printing Comma Seperated String with single quoted values
‘1’,’2′,’3′,’4′,’5′

Leave a Reply

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