简体   繁体   中英

Putting datatable comma separated values in a string

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?

Just a one liner using LINQ .

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

Something like this:

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;
}

Using linq, do it like this:

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

This one fixes your last example

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

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

However, this last approach also would give the result ",1,2,3", so you better rewrite it like this (or use my LINQ variant):

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

How to get datatable column to a Comma Separated string (CSV) in ASP.NET C# using Linq.

Option 1:

string commaSeparatedString = String.Join(",", ds.Tables[0].AsEnumerable().Select(x => x.Field<int>("Data Table Column ID").ToString()).ToArray());

Option 2:

var SelectedValues = ds.Tables[0].AsEnumerable().Select(s => s.Field<int>("Data Table Column ID")).ToArray();
string commaSeperatedValues = string.Join(",", SelectedValues);

Note: Please import package using System.Linq;

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

If dt is the Datatable, then you could loop through the row collection, as:

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

Would this work for you?

we can as also achieve this using below code.

this is my Datatable

DataTable OpDtAdPortalProcessReport = new DataTable();

        OpDtAdPortalProcessReport.Columns.Add("Process Name");
        OpDtAdPortalProcessReport.Columns.Add("Processed On");
        OpDtAdPortalProcessReport.Columns.Add("Status");
        OpDtAdPortalProcessReport.Columns.Add("Comments");

        OpDtAdPortalProcessReport.Rows.Add("7 Miles", "", "gray", "");
        OpDtAdPortalProcessReport.Rows.Add("Active", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt"), "green", "");
        OpDtAdPortalProcessReport.Rows.Add("BMW", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt"), "green", "");
        OpDtAdPortalProcessReport.Rows.Add("Eicoff", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt"), "green", "");
        OpDtAdPortalProcessReport.Rows.Add("Volkswagen", "", "gray", "");
        OpDtAdPortalProcessReport.Rows.Add("Universal", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt"), "orange", "Bot/Script failed to be Executed because of some server issue.");

        Processname = String.Join(",", OpDtAdPortalProcessReport.Rows.Cast<DataRow>().Where(x => x["Status"].ToString().Contains("green")).ToList<DataRow>().Select(c=> c["Process Name"].ToString()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM