Linq query DateTime.Date.DayOfWeek

后端 未结 2 1163
抹茶落季
抹茶落季 2020-12-20 06:05

Trying to get only Thursdays of 1 year back

using (var context = new Context1())
{
      // Get 1 year back only Thursday
      var oneYearEarlier = DateTime         


        
相关标签:
2条回答
  • 2020-12-20 06:42

    LINQ will not recognize the second part of your query into SQL. You need to break your query up in order to perform the filter.

    using (var context = new algoventurelab_db1Context())
    {
          // Go one year back from current date
          var startDate = DateTime.Today.AddYears(-1);
          // This will get all dates in context greater than start date.
          var query1 = (from c in context.Daily25Data
                       where c.Date >= startDate
                       select c).AsEnumerable();
          //this will filter only thurdays
          var query = from c in query1
                      where c.Date.DayOfWeek == DayOfWeek.Thursday
                      select c).ToList();
    
          Console.WriteLine(query);
    }
    
    0 讨论(0)
  • 2020-12-20 06:45

    This is a clever solution using EntityFunctions.DiffDays

    from his post:

    DateTime firstSunday = new DateTime(1753, 1, 7); 
    var bookings = from b in this.db.Bookings 
                   where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1 
                   select b;
    
    0 讨论(0)
提交回复
热议问题