Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting datatable comma separated values in a string

Tags:

c#

asp.net

My datatable consists of a column named "ID". The no. of values in this column varies.Sometimes this Datatable fetches 3 IDs in that ID column, sometimes 2. Now if for example, my datatable has three values as 1,2,3. What I want is to put these three values in a string and separate them by commas as folows:-

string test= "1,2,3";

If Datatable has 2 values, then string should be as follows:-

string test= "1,2";

I did try but in vain. Please help. Thanks.

edit:-

DataTable dt=new DataTable;
 dt = obj.GetIDs();

                for (int i = 0; i < dt.Rows.Count; i++)
                { 
                string test= "What should be here????";
                }

edit 2

 foreach(DataRow dr in dt.Rows)
            {
                string str = str + "," + Convert.ToString(dr("ID"));

            }

@Rajeev ::Tried this..it says dr is a variable but used as a method. What's wrong?

like image 734
Serenity Avatar asked Feb 04 '11 13:02

Serenity


People also ask

How do I convert a DataTable column to a comma separated string?

Select(s => s. Field<string>("Name")). ToArray(); string commaSeperatedValues = string. Join(",", SelectedValues);

What is AC DataTable?

In the ADO.NET library, C# DataTable is a central object. It represents the database tables that provide a collection of rows and columns in grid form. There are different ways to create rows and columns in the DataTable.


1 Answers

Just a one liner using LINQ.

String result = table.AsEnumerable()
                     .Select(row => row["ID"].ToString())
                     .Aggregate((s1, s2) => String.Concat(s1, "," + s2));
like image 170
decyclone Avatar answered Oct 05 '22 12:10

decyclone