Putting datatable values ​​separated by commas in a string

My datatable consists of a column named "ID". No. The values ​​in this column change. Sometimes this Datatable retrieves 3 identifiers in this identifier column, sometimes 2. Now, if, for example, my datatable has three values ​​like 1,2,3. I want to put these three values ​​in a string and separate them with commas as folows: -

string test= "1,2,3";

If the Datatable has 2 values, the line should be as follows: -

string test= "1,2";

I tried, but in vain. Please help. Thank.

edit: -

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

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

change 2

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

            }

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

+3
source share
4 answers

Something like that:

DataTable dt = new DataTable();

string output;
for (int i = 0; i < dt.Rows.Count; i++)
{
    output = output + dt.Rows[i]["ID"].ToString();
    output += (i < dt.Rows.Count) ? "," : string.Empty;
}
+4
source

LINQ.

String result = table.AsEnumerable()
                     .Select(row => row["ID"].ToString())
                     .Aggregate((s1, s2) => String.Concat(s1, "," + s2));
+12

linq, :

var idlist = table.AsEnumerable().Select( r => r.Field<string>("ID")).ToArray();
string result = string.Join(",", idlist);

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

Your problem is what you are trying to call dr("ID"), but dr is not the method implied by your syntax. Use dr["ID"]instead to get your row id column.

However, this last approach will also give the result “1,2,3”, so it’s better to rewrite it like this (or use my LINQ option):

List<string> myIds = new List<string>();
foreach(DataRow dr in dt.Rows)
{
   myIds.Add( Convert.ToString(dr["ID"]));
}
string result = string.Join(",", myIds);
+5
source

If I understand correctly, you have a Datatable that has n rows and 1 column (ID).

If dt is Datatable, you can scroll through the collection of strings like:

For Each dr as DataRow in dt.Rows
  str = str + "," + Convert.ToString(dr("ID"))
Next

Will this work for you?

0
source

Source: https://habr.com/ru/post/1789978/


All Articles