Reputation: 51
I am trying to fetch record from my database year and month vise
I have write following linq
Connection cn = new Connection();
IMongoDatabase db = cn.ConnectionString();
var collection = db.GetCollection<HolidayListModel>("Holiday");
var filter = Builders<HolidayListModel>.Filter.Eq("business_id", businessid);
try
{
var obj = collection.Find(filter).ToListAsync();
if (obj != null && obj.Result != null)
{
if (month == "All")
{
holidaylist = obj.Result.Where(x => DateTime.Parse(x.date).Year == selectedyear).OrderBy(x => DateTime.Parse(x.date)).Select(x => new HolidayListModel()
{
_id = x._id,
business_id = x.business_id,
festival = x.festival,
date = x.date,
day = x.day
}).ToList();
}
else
{
holidaylist = (from x in obj.Result where (( x.date == month )) select x).ToList();
}
Here with lambda expression I got the data year vise using query expression I can't find a way to fetch data using year and month
Can someone guide me how can I write linq for this problem
Upvotes: 2
Views: 63
Reputation: 1063338
This is usually done simply by using a start/end value; so foo.Year == selectedYear
or foo.date == month
becomes simply foo >= @start && foo < @end
(the end is usually exclusive, so for a "year" check, that would be 1 Jan of the next year; for a "month" check it would be the 1st of the next month; this means that times in the last day are still always treated correctly).
If you are storing your dates in mongodb as strings that are ISO 8601 or similar, you could also do the same thing simply with string comparisons, without any "parse" logic.
Upvotes: 1