Search code examples
linqlinq-to-sqldefaultifempty

DefaultIfEmpty for LINQ to a DataTable?


I have a LINQ query written to pull at least one row from a datatable as follows:

var generalQuery =
      from contact in contacts.AsEnumerable().DefaultIfEmpty()
      where contact.Field<String>("CONTACT_TYPE").ToUpper() == "AGENT"
      select new
          {
          AgentName = contact.Field<String>("FIRST_NAME") + " " +
              contact.Field<String>("LAST_NAME"),
          AgentPhoneNumber = contact.Field<String>("PHONE"),
          AgentEmailAddress = contact.Field<String>("EMAIL")
          };

I then try to set the properties of a new instance of a class with the values in the LINQ query output:

var genInfo = new GeneralInformationType
{
    AgentName = generalQuery.FirstOrDefault().AgentName,
    AgentPhoneNumber = generalQuery.FirstOrDefault().AgentPhoneNumber,
    AgentEmailAddress = generalQuery.FirstOrDefault().AgentEmailAddress
}; 

The problem I am running into is that occasionally there are no results in the query. This tries to set the value of the various strings in GeneralInformationType to null and causes exceptions. I tried various methods of DefaultIfEmpty, but can't figure out where to put it.

Any help would be appreciated.

Thanks, Rob


Solution

  • I would recommend removing DefaultIfEmpty() in your generalQuery and adding some logic when generalQuery is empty like so:

    var generalQuery =
          from contact in contacts.AsEnumerable()
          where contact.Field<String>("CONTACT_TYPE").ToUpper() == "AGENT"
          select new
              {
              AgentName = contact.Field<String>("FIRST_NAME") + " " +
                  contact.Field<String>("LAST_NAME"),
              AgentPhoneNumber = contact.Field<String>("PHONE"),
              AgentEmailAddress = contact.Field<String>("EMAIL")
              };
    
    var genInfo = new GeneralInformationType
    {
        AgentName = generalQuery.Any() ? generalQuery.First().AgentName : "Default Name",
       ....
    };