如何在字符串数组中收集数据表结果?

时间:2014-11-14 11:47:26

标签: c# asp.net arrays linq

我有一个包含电子邮件列的表格。它包含一些电子邮件地址。我想把这些细节放到字符串数组中。帮我找一个合适的解决方案。谢谢。

代码:

 alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter EM;
 EM = new alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter();
 DataTable dt = new DataTable();
 dt = EM.GetEmpMail();  

获取电子邮件地址。

编辑:从OP的帖子更新到答案部分

现在我又收到了另一个错误。错误是:"The specified string is not in the form required for an e-mail address."

private void timer1_Tick(object sender, EventArgs e)
 {

  alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter EM;
  EM = new alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter();
  DataTable dt = new DataTable();
  dt = EM.GetEmpMail();

  string[] emails = dt.AsEnumerable().Select(x => x.Field<String>("Email")).ToArray();

  MailMessage loginInfo = new MailMessage();
  loginInfo.To.Add(emails.ToString()); // error popup here.
  loginInfo.From = new MailAddress("fromID@gmail.com");
  loginInfo.Subject = "Hai";

  loginInfo.Body = "Hai";
  loginInfo.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com";
  smtp.Port = 587;
  smtp.EnableSsl = true;
  smtp.Credentials = new System.Net.NetworkCredential("fromID@gmail.com", "***");
  smtp.Send(loginInfo);

 }

3 个答案:

答案 0 :(得分:1)

您可以将LINQ用于您的目的:

dt = EM.GetEmpMail();

string[] emails = dt.AsEnumerable()
                    .Select(x=>x.Field<String>("Email"))
                    .ToArray(); 

最初,我们使用名为DataTable的{​​{1}}扩展方法获取数据表行的序列。我们从行序列中选择,我们得到名称为Email的列的值。

答案 1 :(得分:1)

所以您希望所有电子邮件都为String[]?您可以使用Linq-To-DataTable。使用DataRow.Field仅选择电子邮件列。

string[] emails = dt.AsEnumerable().Select(row => row.Field<String>("Email")).ToArray();

答案 2 :(得分:1)

您可以添加带循环的电子邮件并发送。

试试这个

private void timer1_Tick(object sender, EventArgs e)
    {

        alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter EM;
        EM = new alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter();
        DataTable dt = new DataTable();
        dt = EM.GetEmpMail();

        string[] emails = dt.AsEnumerable().Select(x => x.Field<String>("Email")).ToArray();

        MailMessage loginInfo = new MailMessage();
        foreach (var email in emails)
        {
            loginInfo.To.Add(email);
        }

        loginInfo.From = new MailAddress("fromID@gmail.com");
        loginInfo.Subject = "Hai";

        loginInfo.Body = "Hai";
        loginInfo.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.Credentials = new System.Net.NetworkCredential("fromID@gmail.com", "***");
        smtp.Send(loginInfo);

    }