Selecting Multiple Rows from DataTable using Linq

Farzaneh Talebi picture Farzaneh Talebi · Apr 12, 2016 · Viewed 9.7k times · Source

I have a DataTable that has these columns:

AlertEmail , ClosingDate , OpeningDate , LocationTitle , JobTitle

I want to Search this DataTable and find Records for each AlertEmail. I do this but MailInfo returned 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));
    }
}

What was wrong in my code?

Answer

Viru picture Viru · Apr 12, 2016

As mail is object of anonymous class...Accessing its property will solve your problem instead of 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")
                   };