Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check DateTime for null in linq expression

Tags:

c#

datetime

linq

Is where a way to check if DateTime is null in linq expression? I've IEnumeable method where I'm returning data from database

return _requestRepository.ExecuteProcReader(
   myRequest,
   new SqlParameter("@userName", user)).Select(items => new Feed
{
   Id = (int)items[0],
   Title = items[1].ToString(),
   Body = items[2].ToString(),
   Link = items[3].ToString(),
   PubDate = (DateTime) items[4]
});

And items[4] is a datetime which can be null in database. So, how can check something like

if(items[4] is DateTime)
{
   PubDate = (DateTime) items[4]
}
like image 978
semper fi Avatar asked Oct 31 '22 05:10

semper fi


1 Answers

One more option would be to declare PubDate as nullable inside class Feeddeclaration.

Like this:

class Feed {
  public DateTime? PubDate {get;set;}
  ...
}

This will expose truth from database into data access layer and shift your null checks one level up.

See: Nullable types in c#

like image 120
George Mamaladze Avatar answered Nov 13 '22 03:11

George Mamaladze