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.
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
Iterate each
DataRow
and get the value fromDataColumn
.Add value into array/list.
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
Working with System.Linq to get the email as
List<string>
.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());