0

I want to display last 3 months sales records.Based on current month will show it's previous records in linq to sql.Please tell me the query for that.

If current month is june then will show apr,may,june records.

id name  no.ofsales  desc          datevalue
1  test    12        test desc     2013-10-12 
2  test1   16        desc message  2013-09-14

Give me idea on this query.

user1237131
  • 1,853
  • 3
  • 26
  • 35
  • 5
    I see no date information in this data. How could you query off the date, if there is no date information? – Dan Sep 05 '13 at 06:24
  • http://stackoverflow.com/questions/214426/how-to-compare-dates-in-linq – uowzd01 Sep 05 '13 at 06:36

3 Answers3

3
var minDate = DateTime.Now.AddMonths(-3);

from x in datatable
where x.datevalue> minDate
select x;
David
  • 710
  • 5
  • 15
1
from x in datatable
where x.datevalue> DateTime.Now.AddMonths(-3) 
orderby x.id ascending
select x;
Bibhu
  • 4,053
  • 4
  • 33
  • 63
  • Same i am trying but giving error linq to entities does not have Datetime.Now.AddMonths() like error.LINQ to Entities does not recognize the method 'System.DateTime AddMonths(Int32)' method, and this method cannot be translated into a store expression. – user1237131 Sep 05 '13 at 06:39
1

I think something like this could work:

yourCollection.Where(x => 
    DateTime.Compare(x.DateTimeProperty, DateTime.Today.AddMonths(-3)) >= 0);
Teeknow
  • 1,015
  • 2
  • 17
  • 39
  • mine doesn't group dates like Bidhu's answer though (OP wanted them grouped) – Teeknow Sep 05 '13 at 06:39
  • getting exception.LINQ to Entities does not recognize the method 'System.DateTime AddMonths(Int32)' method, and this method cannot be translated into a store expression. – user1237131 Sep 05 '13 at 06:45
  • in my database my datetimes are saving as 2013-08-12,2013-10-14 .in code we are comapring with Datetime.Now.Addmonths(-3) then getting date format as 08/05/2013 like that .i am not getting previous months results.how to comapre those two dateformats!!! – user1237131 Sep 05 '13 at 09:20
  • Is 2013-08-12 a string when you pull it in? If so it looks like you could use this on x.DateProp inside the lambda function: DateTime.ParseExact(x.DateProp, "yyyy-MM-dd", CultureInfo.InvariantCulture); source: http://stackoverflow.com/questions/11551185/converting-a-string-to-datetime-from-yyyy-mm-dd – Teeknow Sep 06 '13 at 01:06