Vijaychandar
Vijaychandar

Reputation: 714

Retrieving dataset values from a particular column into a string

In my application, I want to get the data in particular column in dataset and convert it to a string with comma seperation. I've used the code below. But I think it makes the application very slow.

string ids = "";
if (datatable1.Rows.Count > 0)         
{
       foreach (DataRow dr in datatable1.Rows)
       {
           ids += dr["id"].ToString() + " ,";
       }

}

Can anyone provide some suggestion to improve the code.

Upvotes: 0

Views: 725

Answers (1)

Habib
Habib

Reputation: 223247

Use StringBuilder if you are doing too many concatenation.

StringBuilder ids = new StringBuilder();
if (datatable1.Rows.Count > 0)         
{
       foreach (DataRow dr in datatable1.Rows)
       {
           ids.Append(dr["id"].ToString() + ",");
       }

}

Or you may shorten it using string.Join

string ids = string.Join(",",datatable1.AsEnumerable()
                                       .Select(r=> r.Field<int>("ID")));

Upvotes: 3

Related Questions