Getting all my posts for a specific period (lambda expression) - asp.net

I would like a lambda expression to get all my posts with a PublishDate in a specific month / year range (like 10/2011).
public IEnumerable<Post> SearchPosts(string periode)
{
// periode may be 10/2011 so I would like all posts from 10/01/2011 to 10/31/2011
return m_PostRepository.GetPosts().Where(x => x.PublishDate...?
}

Description
You can do this using the DateTime properties Year and Month in your Where Filter.
Sample
return m_PostRepository.GetPosts().Where(x => x.PublishDate.Year == 2011 &&
x.PublishDate.Month == 10).ToList();
More Information
MSDN - DateTime.Month Property
MSDN - DateTime.Year Property
Update after a comment from Bronzato
DateTime? date;
// does date has a value ? If yes, apply the filter. If not return everything.
if (date.HasValue)
{
return m_PostRepository.GetPosts().Where(x => x.PublishDate.Year == date.Value.Year &&
x.PublishDate.Month == date.Value.Month).ToList();
} else return return m_PostRepository.GetPosts();

You can also try it like this (working with PublishDate as Nullable<DateTime>):
DateTime date;
if (DateTime.TryParseExact(value, "MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
var result = m_PostRepository.GetPosts().Where(x => x.PublishDate.HasValue &&
x.PublishDate.Value.Month == date.Month &&
x.PublishDate.Value.Year == date.Year).ToList();
}

public IEnumerable<Post> SearchPosts(string periode){
string[] _periode = periode.Split("/");
return m_PostRepository.GetPosts().Where(x => x.PublishDate.year = convert.ToInt16(_periode[1])).Where(x => x.PublishDate.Month= convert.ToInt16(_periode[0]))}

Related

Angular 12 kendo-datepicker disable past dates

I want to disable Past dates in Kendo Date Picker. How can I do?
<kendo-datepicker [(value)]="oneTime.startDate" [disabled]="disableDates()"></kendo-datepicker>
disableDates() {
//return (this.currentDate.getTime() (new Date()).getTime());
}
<kendo-datepicker [(value)]="startDate" [disabledDates]="disabledDates"></kendo-datepicker>
public disabledDates = (date: Date): boolean => {
const yesterday = (d => new Date(d.setDate(d.getDate() - 1)))(new Date);
return (date.getTime() < yesterday.getTime());
};

ASP.NET MVC 5 using DateTime

I am working on a project for an Event application. My task is to create a partial view and show any events that are within the next two days.
I am getting an error:
Operator <= cannot be applied to operands of type string and DateTime
I am unsure how to fix this issue.
Here is my code:
public ActionResult GetLastMinuteDeals()
{
DateTime futureDate = DateTime.Today.AddDays(2);
var LastMinuteDeal = db.Events
.Where(a => a.EventStartDate <= DateTime.Today)
.Where(a => a.EventStartDate <= futureDate);
return LastMinuteDeal;
}
The member EventStartDate is likely a string type. To compare them to a DateTime, you will need to create another DateTime object, like so:
var LastMinuteDeal = db.Events
.Where(a => DateTime.Parse(a.EventStartDate) <= DateTime.Today)
.Where(a => DateTime.Parse(a.EventStartDate) <= futureDate);

Check Date is tomorrow in C#.net

I write some code to check that now date is tomorrow :
re_dat = SDKClass.Selct_Date_now(); // return today date from database.
DateTime date_now = DateTime.Parse(re_dat).Date;
if (date_now == DateTime.Now.AddDays(1).Date)
{
response.write("tomorrow");
}
but condition doesn't fire.
thanks a lot.
If your question is about difference with some dynamic input date and today date as reference date, then you can use dates difference like this:
var dateDiff = (DateTime.Today - inputDate.Date).TotalDays;
Here is my simple version of date formatting:
public static string GetDateString(DateTime inputDate)
{
var dateDiff = (DateTime.Today - inputDate.Date).TotalDays;
if (dateDiff == 0)
{
return "TODAY";
}
else if(dateDiff == 1)
{
return "YESTERDAY";
}
else if(dateDiff == -1)
{
return "TOMORROW";
}
else
{
return inputDate.ToShortDateString();
}
}
you shouldn't retrive the today date from database.
i think best solutin for this:
if (DateTime.Today == DateTime.Today.AddDays(1))
{
Response.Write("Tomorrow");
}
else { //Write whatever you want }

ASP.NET check if LinqToEntities returned something or not

How to make this method return boolean value, depending on query return. False - nothing, True - data exists. Before i just returned int from uniqueQuote.Count() but does not look like great method. Thank you!
private bool CheckEnquiryUser(int enquiryId, Guid userId)
{
int selectedEnquiryId = enquiryId;
Guid currentUserId = userId;
Entities ctx3 = new Entities();
var uniqueQuote = from quot in ctx3.Enquiries.Include("aspnet_Users")
where quot.EnquiryId == selectedEnquiryId &&
quot.aspnet_Users.UserId == currentUserId
select quot;
bool exist = uniqueQuote;
return exist;
Use the Enumerable.Any method:
return uniqueQuote.Any();
Or pass the predicate to it directly:
return ctx3.Enquiries.Include("aspnet_Users")
.Any(quot => quot.EnquiryId == selectedEnquiryId
&& quot.aspnet_Users.UserId == currentUserId);
I'm more used to this format, but you can translate to use .Any
return ctx3.Enquiries.Include("aspnet_Users")
.Any(x=> x.EnquiryId == selectedEnquiryId &&
x.aspnet_Users.UserId == currentUserId);
Try something like:
return uniqueQuote.Count() > 0;

The best way to build Dynamic LINQ query

Hi I am looking for best method for writing Dynamic LINQ query.
I have a function like
public IQueryable<Student> FindByAllStudents(int? id, string Name, int? CourseID, bool? IsActive) // like this way, all field values are passed
{
// code for compairision
return db.Student;
}
we can also write db.Students.where(predicate)
or
a query like
var students = from s in db.students where s.Name.Contains(Name)
s.ID.Equals(id)
//and so on....
So will this method works if i don't pass ID (i.e. Null)?
is proper way for all the datatypes?
The point is function can have all null values as a parameter for equivalence of select * from statement.
can any one help me to build best query with sample code?
Okay, it's not entirely clear what you want, but if you're trying to only add where clauses for the parameters which are non-null, you could do:
public IQueryable<Student> FindByAllStudents
(int? id, string name, int? courseID, bool? isActive)
{
IQueryable<Student> query = db.Student;
if (id != null)
{
query = query.Where(student => student.ID == id.Value);
}
if (name != null)
{
query = query.Where(student => student.Name.Contains(name));
}
if (courseID != null)
{
query = query.Where(student => student.CourseID == courseID.Value);
}
if (isActive != null)
{
query = query.Where(student => student.IsActive == isActive.Value);
}
return query;
}
I haven't tried that, and it's possible that LINQ to SQL would get confused by the code to find the value of the nullable value types. You may need to write code like this:
if (courseID != null)
{
int queryCourseID = courseID.Value;
query = query.Where(student => student.CourseID == queryCourseID);
}
It's worth trying the simpler form first though :)
Of course, all this gets a bit irritating. A helpful extension method could make life more concise:
public static IQueryable<TSource> OptionalWhere<TSource, TParameter>
(IQueryable<TSource> source,
TParameter? parameter,
Func<TParameter, Expression<Func<TSource,bool>>> whereClause)
where TParameter : struct
{
IQueryable<TSource> ret = source;
if (parameter != null)
{
ret = ret.Where(whereClause(parameter.Value));
}
return ret;
}
You'd then use it like this:
public IQueryable<Student> FindByAllStudents
(int? id, string name, int? courseID, bool? isActive)
{
IQueryable<Student> query = db.Student
.OptionalWhere(id, x => (student => student.ID == x))
.OptionalWhere(courseID, x => (student => student.CourseID == x))
.OptionalWhere(isActive, x => (student => student.IsActive == x));
if (name != null)
{
query = query.Where(student => student.Name.Contains(name));
}
return query;
}
Using a higher order function like this could get confusing if you're not really comfortable with it though, so if you're not doing very many queries like this you might want to stick with the longer but simpler code.

Resources