使用 Linq 从 DataTable 中选择多行

Selecting Multiple Rows from DataTable using Linq

我有一个 DataTable 包含这些列:

AlertEmail , ClosingDate , OpeningDate , LocationTitle , JobTitle

我想搜索此 DataTable 并查找每个 AlertEmail 的记录。我这样做了,但是 MailInfo 返回了 NULL.

DataTable dt = amail.GetAllJobAlertForSend();

var AllEmail = dt.AsEnumerable()
                 .Select(row => new {attribute1_name = row.Field<string>("AlertEmail") }).Distinct();

foreach (var mail in AllEmail)
{
    var MailInfo = from p in dt.AsEnumerable()
                   where p.Field<string>("AlertEmail").Trim() == mail.ToString()
                   select new
                   {
                       ClosingDate = p.Field<DateTime>("ClosingDate"),
                       OpeningDate = p.Field<DateTime>("OpeningDate"),
                       LocationTitle = p.Field<string>("LocationTitle"),
                       JobTitle = p.Field<string>("JobTitle")
                   };

    foreach (var info in MailInfo)
    {
        Response.Write(string.Format("{0}", info.ClosingDate));
    }
}

我的代码有什么问题?

由于邮件是匿名对象 class...访问它的 属性 将解决您的问题而不是 ToString

 var MailInfo = from p in dt.AsEnumerable()
                   where p.Field<string>("AlertEmail").Trim() == mail.attribute1_name
                   select new
                   {
                       ClosingDate = p.Field<DateTime>("ClosingDate"),
                       OpeningDate = p.Field<DateTime>("OpeningDate"),
                       LocationTitle = p.Field<string>("LocationTitle"),
                       JobTitle = p.Field<string>("JobTitle")
                   };