Home > Net >  Get column results from DataTable into a string
Get column results from DataTable into a string

Time:06-25

I have a select statement that returns data to a DataTable. About 3-5 columns and 5-10 rows. I'm trying to collect all the data from the "Email" Column and add it to a single-line string.

Email name phone
[email protected] frank 213-444-1911
[email protected] shawn 213-444-1092
[email protected] chloe 213-444-1229
[email protected] shane 213-444-1769

Result:

[email protected];[email protected];[email protected];[email protected]

CodePudding user response:

Solution 1

  1. Iterate each DataRow and get the value from DataColumn.

  2. Add value into array/list.

  3. Convert array/list to string with String.Join() with ; as separator.

using System.Collections.Generic;

List<string> emails = new List<string>();

foreach (DataRow row in dt.Rows)
{
    emails.Add(row["Email"].ToString());
}

string result = String.Join(";", emails);

Solution 2

  1. Working with System.Linq to get the email as List<string>.

  2. Convert array/list to string with String.Join() with ; as separator.

using System.Linq;

string result = String.Join(";", dt.AsEnumerable()
                                      .Select(x => x["Email"].ToString())
                                      .ToList());

Sample .NET Fiddle

  • Related