maztt
maztt

Reputation: 12294

asp.net mvc datettime linq check for empty

var postsidebar = from post in postrepository.GetAllPosts()
    join pstmt in postrepository.GetAllPostMetas()
    on post.int_PostId equals pstmt.int_PostId
    where (post.int_PostTypeId == 4 
        && post.int_PostStatusId == 2 
        && post.int_OrganizationId == layoutrep.GetSidebarDetailById(SidebarDetailsId).int_OrganizationId)
        && (pstmt.vcr_MetaKey.Contains(filter) && pstmt.vcr_MetaValue.Contains("true")     
        && (System.DateTime.Now >= 
            Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m => 
                m.vcr_MetaKey == "Publish Date").vcr_MetaValue))) 
    select post;

how can i check for empty in this part in Date(it is giving error)

&& (System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m => 
    m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))

Upvotes: 0

Views: 141

Answers (2)

hunter
hunter

Reputation: 63522

You could try eliminated the possibility of an empty value first and then try your cast afterward.

&& pstmt.Post.PostMetas.FirstOrDefault(m => 
    m.vcr_MetaKey == "Publish Date"
    && !string.IsNullOrEmpty(m.vcr_MetaValue))
&& (System.DateTime.Now >= 
        Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m => 
            m.vcr_MetaKey == "Publish Date").vcr_MetaValue))) 

Upvotes: 1

danijels
danijels

Reputation: 5291

Try this:

// declare the action for re-use
Func<PostMeta,bool> action = m => m.vcr_MetaKey == "Publish Date";

// then test for Any() before comparing anything
&& (pstmt.Post.PostMetas.Any(action) && System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.First(action).vcr_MetaValue)))

Upvotes: 0

Related Questions