0

我在发布日期列中有这些记录,它们是字符串。我想在 LINQ to SQL 中的两个日期之间进行查询。查询正确日期并忽略无效日期的最合适方法是什么?

published date

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

下面的代码解决了我的问题,但是对于大型记录来说非常耗时,而且它不是 LINQ to 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();
4

1 回答 1

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

于 2013-11-01T11:58:28.410 回答