-1

I see a lot of complex examples for converting a DataTable with multiple-member rows here but in my case, the query simply returns one column from a table, that is to say 0..N strings/varchars, such as:

bbfinaleofseem@wallacestevens.org
eyenoy@dunbar.com

I thought something like this should work:

DataTable UnitReportPairEmailValsDT = new DataTable();
string qry = string.Format(SQL.UnitReportPairEmailQuery, unit, rptId);
UnitReportPairEmailValsDT = SQL.ExecuteSQLReturnDataTable(
    qry,
    CommandType.Text,
    null
    );

List<String> emailAddresses = new List<string>();
foreach (string emailaddr in UnitReportPairEmailValsDT)
{
    emailAddresses.Add(emailaddr);
}

...but it won't compile ("foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator'")

I tried appending ".AsEnumerable" to "in UnitReportPairEmailValsDT" too, but that also provoked the wrath of the compiler.

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

3 Answers3

2

Error says you cannot loop through DataTable object itself, probably what you need is looping through DataRows.

Use this.

foreach(DataRow row in UnitReportPairEmailValsDT.Rows)
{
     emailAddresses.Add(row["emailaddr"].ToString()); // assuming you have emailaddr column.
}

Other option, use Linq

emailAddresses = UnitReportPairEmailValsDT
                         .AsEnumerable()
                         .Select(row=> row.Field<string>("emailaddr"))
                         .ToList();
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
2

try something like this:

List<String> emailAddresses = new List<string>();
foreach (DataRow row in UnitReportPairEmailValsDT.Rows)
{
    emailAddresses.Add(row.Item(0));
}
1

Suppose dt is your data table then using Linq: dt.Rows.Select(x=> x[0]+"").ToList() will give you List. Beware of using Select(x=>xToString()) as it is prone to error if column value is null. x[0]+"" makes sure that in case of null empty string is returned.

Mukesh Adhvaryu
  • 642
  • 5
  • 16