使用Linq

时间:2016-04-12 08:20:59

标签: c# linq datatable linq-to-dataset

我有DataTable有这些columsn:

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));
    }
}

我的代码出了什么问题?你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

由于邮件是匿名类的对象...访问其属性将解决您的问题,而不是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")
                   };