2013-11-01 206 views
0

我在發佈的日期列中有這些記錄是字符串。我想在LINQ to SQL中的兩個日期之間進行查詢。查詢正確日期並忽略無效日期的最恰當方法是什麼?LINQ to SQL查詢日期

published date 

jan 
11-oct 
2010-09-09 
feb 
feb-12 

下面的代碼解決我的問題,但它是非常耗時的大記錄,它不是LINQ到SQL。

Func<string, DateTime?> tryToGetDate = value => 
{ 
    DateTime dateValue; 
    return DateTime.TryParse(value, out dateValue) ? (DateTime?)dateValue : null; 
};  


var dates = (from bookdetails in bookcategories 
      let dateValue = tryToGetDate(bookdetails.PublishedDate) 
      where dateValue != null 
      && (DateTime)dateValue >= twomonths 
      && (DateTime)dateValue <= today 
      orderby bookdetails.PublishedDate descending, bookdetails.BookId 

      select new BookInfo 
      { 
       BookId = bookdetails.BookId, 
       BookTitle = bookdetails.Title, 
       Images = bookdetails.ThumbnailImagePath, 
       PublishDate = bookdetails.PublishedDate, 
       AuthorList = bookdetails.BookAuthors.Select(q => q.Author.Author1).ToList(), 
       CategoryList =bookdetails.BookCategories.Select(q=>q.Category.CategoryName).ToList()        
      }).Take(2).ToList(); 
+0

更好的你應該去的日期列,並從那裏濾除天,月份或年份或您需要的任何組合。用字符串,你將面臨解析問題... –

+0

我希望我能,但問題是,我不能。 – maztt

+0

爲什麼你的日期'DateTime'在數據庫中? – Arran

回答

0

快速的解決方案是

var dates = (from bookdetails in bookcategories 
     where SqlFunctions.IsDate(bookdetails.PublishedDate)==1 
     orderby bookdetails.PublishedDate descending, bookdetails.BookId) 
     .ToList() 
     .Where.(b=> Convert.ToDateTime(b.PublishedDate) >= twomonths 
       && Convert.ToDateTime(b.PublishedDate) <= today); 

但是,如果你還想要更多的性能應該映射「轉換爲日期」功能的SQL