Linq query filter by date (Month and year)
Solution 1
Looks like you should be able to do:
// Type and property names changed to match .NET conventions
public IEnumerable<Content> GetContents(int year, int month)
{
return db.Contents // Or wherever you're getting data from
.Where(c => c.Date.Year == year && c.Date.Month == month);
}
I've split out year
and month
as separate parameters, as that's how you described them - if you really want to be able to handle "01/2013" you would probably want to just split by '/'
and parsing each of the pieces as an integer first. (Alternatively, parse it as a date in a specific format and then take the year and month from that.)
EDIT: Note that formatting each value as a string is pointless and potentially incorrect unless you're careful. (For example, unless you specify the culture explicitly, if you use /
in the pattern you'll get the current culture's date separator, which may well not be what you expect.)
You're not actually trying to match a string pattern - you're trying to test for the year and month of the date. That's what the code above expresses clearly. String formatting is an irrelevance.
Solution 2
This is correct for only moth and year
List<eTransaction> lsttrans = db.eTransactions.Where(c => c.SchemeID == scid &&
c.DateOfPay.Value.Month == month && c.DateOfPay.Value.Year == year).ToList();
Tun
Updated on July 09, 2022Comments
-
Tun almost 2 years
public class content { public int Id { get; set; } public string name { get; set; } public DateTime date { get; set; } } Id name date 1 content1 01/01/2013 2 content2 05/01/2013 3 content3 05/03/2013 4 content4 01/06/2013 5 content5 10/03/2012 6 content6 01/01/2012
I'm trying that if query passes '01/2013', query should return content id 1,2 . Is there anyone knows how to query above situation ?
-
Jon Skeet almost 11 years"Is that right way to do ?" - not in my view, no. You're not logically performing a string comparison; you're performing a month and year comparison. So convert your input data into a month and year first, and use those values to compare the month and year of each element.