How to get the month wise records in c#? - c#

My Table like this.
name date phonenumber
venky 25-06-2013 123123123
vasud 27-06-2013 2423727384
sdfds 14-06-2013 12312332132
If user want to see june month records then he pass 06 as input parameter how to write linq to sql query to get june month records as output..

Well it sounds like you just want something like:
public IQueryable<Record> GetRecordsForMonth(int month)
{
return new RecordContext().Where(record => record.Date.Month == month);
}
That's assuming your date field in the database is actually an appropriate datetime field or something similar. If it's not, then fix your schema.
Alternatively, for dates within a range, you could take two DateTime values in the method and filter that way:
public IQueryable<Record> GetRecordsForMonth(DateTime minDateInclusive.
DateTime maxDateExclusive)
{
return new RecordContext().Where(record => record.Date >= minDateInclusive
&& record.Date < maxDateExclusive);
}

Related

Get Next Meeting Date fails using Linq query

I need to display the next Meeting Date from a table of meeting dates. Once a date passes as current, the next date is supposed to show up. I've searched for similar examples but no luck:
05/21/2019
07/11/2019
08/08/2019
09/12/2019
10/10/2019
11/14/2019
12/12/2019
Here the Linq query I have that fails. It doesn't return anything for example after the 10/10/2019 date because 11/14/2019 is actually more than 1 month.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date && c.MeetingDate.Date <= DateTime.Now.Date.AddMonths(1)
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}
Also, I am pretty sure something odd is going to happen on the last month of the year after the meeting happens (December).
I am trying to show the current next meeting, and have it change to the next meeting after that once the current one is over. Adding a month to 12 will create a month number 13 which is non-existent.
You can sort meeting schedule ascending after filtering out dates that have already happened then just grab the first one.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date
orderby c.MeetingDate.Date
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}

LINQ to entites does not recognize Convert.ToDatetime method

EDIT All the other answers that link to a previous question's wont work for me because they are either using two tables or they know what startdate they are looking for.
I have the following LINQ query where i am trying to get the data from a table for the last 14 days. LINQ does not recognize Convert.ToDatetime method. The Query_Date column is a type string and i can't change it. How do i get the data i need?
var logs = (from bwl in db.UserActivities
where Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
So i couldn't get what i wanted because i would have to make too many changes so the workaround i am doing is: I am using this code
var logs = db.UserActivities.ToList().Take(100);
This will get me the last 100 entries. I will give options for more or less entries then they can filter it on date in the search bar on the datatable.
It's not great but time is against me and this will suffice.
Do you have data being entered at least every day? If so, what about something like this:
var oldestDate = DateTime.Now.AddDays(-14);
var dateString = oldestDate.ToString(*/ your date format */);
var oldestID = db.UserActivities.First(b => b.Query_Date == dateString).Id;
var logs = (from bwl in db.UserActivities
where bwl.Id > oldestID
select new {
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
Basically you find a record on that date and use its ID as a proxy for the date. This only works in certain circumstances (i.e. if the IDs are in date order).
This also isn't guaranteed to be the oldest entry on that date, but that could be achieved either by using ID order:
var oldestID = db.UserActivities.Where(b => b.Query_Date == dateString)
.OrderBy(b => b.Id)
.First().Id;
Or more lazily by using -15 instead of -14 when you add days, if you don't mind grabbing an unknown percentage of that 15th day.
Convert.ToDateTime works if your Query_Date has proper format. If not, check your string expression is convertable format.
I tested below code and it works fine when I assume Query_Date is a form of DateTime.toString().
var logs = (from bwl in db.UserActivities
where DateTime.Now - Convert.ToDateTime(bwl.Query_Date) <= TimeSpan.FromDays(14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
I also tested with your where expression Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14) and confirmed that it gives same result.

LINQ Query against Azure table service fails

I have a few records saved in my Azure Table Storage. I'm trying to pull records from a table,for only a particular day/date, for the currently logged in user.
My query returns nothing, so my list is always empty, even though I know that I have 3 records for this month, in my table.
I'm not sure why the query fails in this case. How do I pull records for a specific date, for a specific user? Any help?
This is what I've tried so far:
public async Task<Result<List<Alert>>> FetchAlertsForDate (DateTime date)
{
try {
var fromDate = new DateTime(date.Year,date.Month,date.Day,0,0,0); //lets create a 12:00:00 AM date
var toDate = new DateTime(date.Year,date.Month,date.Day,23,59,59); //lets create a 23:59:59PM date
var alertTable=client.GetSyncTable<Alert>();
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId).Where(n=> n.StartDate >= fromDate && n.StartDate <= toDate).ToListAsync();
return Result<List<Alert>>.Success(alerts);
} catch (Exception ex) {
return Result<List<Alert>>.Failure (ex.Message + ex.StackTrace);
}
}
The code you have written contains no obvious bugs to answer your question
How do I pull records for a specific date, for a specific user?
Rather than a date range you use in your method you can just compare the date part of a dateTime like this;
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId).Where(n=> n.StartDate.Date == date.Date).ToListAsync();
I think you can do away with the second where clause too;
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId && n.StartDate.Date == date.Date).ToListAsync();
If you are not getting any records then for that specific combination of userId and Date then the most likely thing is that there aren't any records with that exact combination.
For some reason, the same query ended up working. I improved on it by removing the first part, where I was checking for the current user's id. That wasn't necessary since in my case.
So the final query looks like this:
var alerts = await alertTable.Where(n=> n.StartDate >= fromDate && n.StartDate <= toDate).ToListAsync();
This now pulls up all the logged in user's details.

Query Mongo Database for Records on a Single Day

My requirement is a simple one. I have some Mongo documents which contain a startTime (a DateTime field) and I want to query the containing collection for all of the documents that have a startTime on a particular day.
For example, I want all documents which have a date "22/10/2015", I don't care about the time component, I just want all documents that have that date.
I have written the following method to attempt to do this
public static async Task<List<uint>> DateRangeToEventIDAdapter(
MongoClient client, DateTime startDate, DateTime endDate, int? limit,
IProgress<string> progress, CancellationToken token)
{
if (startDate == endDate)
endDate = endDate.AddDays(1.0);
var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Gte(
MatchDetailsFields.START_TIME, BsonDateTime.Create(startDate.ToUniversalTime()));
filter = filterBuilder.And(filter, filterBuilder.Lte(MatchDetailsFields.START_TIME,
BsonDateTime.Create(endDate.ToUniversalTime())));
// Use Filter to get collection here...
}
[using C# Driver 2.0]. My problem case is when startDate == endDate, if I just use Eq. this returns zero records. So I attempt to add 24 hours to the time of the startDate for the endDate and then use .Lte and .Gte - this dow not work and returns both days.
This seems SOOOOO simple, but yet I can get Mongo to return what I want. What filter should I be using to retrieve all documents that occur on a specified day?
Thanks for your time.
This works for me (you should be using Lt and not Lte):
var theDay = new DateTime(2015,10,22).ToUniversalTime();
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Gte( "startTime" , theDay ) &
builder.Lt( "startTime", theDay.AddDays(1) ) ;
var list = await col.Find( filter ).ToListAsync();
You might code it as:
endDate = endDate.Date.AddDays(1);

Show data between a date range

Greetings
I have the personal data of an individual including birth date
How do I get the information of people born between the date 1 and date 2?
date of birth is in a SQL Server database Compact
I get a record this way
using (ISession session = NHibernateConfiguration.OpenSession())
{
var production = session
.CreateCriteria(typeof(Person))
.Add(Restrictions.Eq("Date", date))
.List<Person>();
return production;
}
instead of .Add(Restrictions.Eq("Date", date)) use .Add(Restrictions.Between("Date", fromDate, toDate))
If you have these Object's Stored on a List than you could say ,
for(int i=0;i<list.count;i++)
{
if(list[i].getBirthdate.Day == 1 || list[i].getBirthdate.Day == 2 )
//DoSomething
}
But man ,you should be more Specific ,if these Information's are Stored in DataBase ,if Birth Date is Stored As Formated DateTime or whatever ,please be more specific and show us some code.
By the tags in your question, it looks like you're using Nhibernate. If you use Linq-to-Nhibernate, then you could use a linq statement like this:
var query = myISession.Linq<Person>();
var result = from entity in query
where entity.Dob >= dob1 && entity.Dob <= dob2
select entity;
return result.Count() > 0 ? result.ToList() : null;
I like extensions methods much more
var persons = GetPersonList();
var range = persons.Where(p => p.Dob >= startDate && p.Dob <= endDate);
Note that I know this is basically the same as using LINQ syntax, I just don't like linq syntax :).

Categories

Resources