LINQ querying for multiple dates and counting rows - c#

Hi I want to know how to do two things with LINQ
This question is probably more a SQL/C# thing I firstly want to query with multiple dates
How would I do this?
For example I want to query every date in 2011 in a DateTime SQL Column So I want to find 01/01/2011 to 31/12/2011 I guess I would replace the first day month numbers with something e.g ##/##/2011
Secondly how do I count rows would it be like this "var rowCount = qRows.Count();"
Thanks

try this :
List<Order> ord = (from o in dc.Orders
where o.OrderDate.Value.Year == 2011
select o).ToList();
int Count = ord.Count;

from x in somethingwithdate
where x.adate > '1/1/2000'
where x.adate < '1/1/2010'
select x
you can also do x.Count

You can do myDate.AddDays(1) repeated as many times as necessary.
Yes, you can do a Count() on the returned LINQ dataset.

Slightly different take on earlier answer(if you were pulling the date from another object for instance):
DateTime myDate = new DateTime(2011,1,1);
var results = (from t in dc.events
where t.event_date.Value.Year.Equals(myDate.Year)
select t).ToList();
int testCount = results.Count();

Related

How works datetime and How to compare two dates in windows form ADO Entities?

I have table "Deposit" in my database sql server with column "DepositDate" and it's type is datetime.
I have rows with todays date and one of them is 2019-02-14 22:26:50.000
And Today's date is the same , I mean 2019-02-14
But when try to get all todays row by following code, it doesn't work. I think it has something with those time that follow the date to do.
But write now I'am intreseted only day but I want to keed datetime type in my database.
So Must even time mutch with date I'am searching? I use Linq and Entities
I do like this , I do not get error but do not find the row. returning empty datagridview
DateTime TodayDate = Convert.ToDateTime(DateTime.Now.ToString());
var deposit = (from u in db.Deposit
where u.DepositDate == TodayDate
select u).ToList();
if (deposit != null)
{
dgvDeposit.DataSource = null;
dgvDeposit.DataSource = deposit;
}
I tried even But I get erroe
date is not supported in LINQ to ADO Entities
DateTime TodayDate = Convert.ToDateTime(DateTime.Now.Date);
where u.DepositDate.Value.Date == TodayDate
I really appreciate your help
You have to filter between a start and end date if you want to make use of whatever indexes you might have on DepositDate. If you do not care about that there are Canonical Date Functions you can use to strip the time from the database value.
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
var deposit = (from u in db.Deposit
where u.DepositDate >= today && u.DepositDate < tomorrow
select u).ToList();
Or as a lambda
var deposits = db.Deposit
.Where(u => u.DepositDate >= today && u.DepositDate < tomorrow)
.ToList();
As a side note and also a matter of opinion it generally recommended to pluralize DbSet<T> properties on your DbContext (like db.Deposits). The same goes for your variable deposit as it will be of type List<Deposit> which is a collection (the 2nd code sample I changed it).

How write query for getting last 3 months records in linq to sql?

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.
var minDate = DateTime.Now.AddMonths(-3);
from x in datatable
where x.datevalue> minDate
select x;
I think something like this could work:
yourCollection.Where(x =>
DateTime.Compare(x.DateTimeProperty, DateTime.Today.AddMonths(-3)) >= 0);
from x in datatable
where x.datevalue> DateTime.Now.AddMonths(-3)
orderby x.id ascending
select x;

Using Entity Framework, return all rows with date port of DateTime column equal to today

I'm using entity framework to work with a MySql database. I have a DateTime column that I want to query and return all rows where the date portion of the DateTime column's values are within the range of the current day.
I'm assuming the DateTime property is not normalized to day, so that it may have any value throughout the day.
The most straightforward way staying in Entity Framework land is probably something like:
DateTime today = DateTime.Today; // earliest time today
DateTime tomorrow = DateTime.Today.AddDays(1); // earliest time tomorrow
var q = db.Objects
.Where(x => x.Time >= today)
.Where(x => x.Time < tomorrow);
This is a general technique that can find any range of times (not just specific days).
If the table has or will have many rows, you'll want to check that it is indexed to prevent having to scan the entire table.
Using LINQ to Entities:
private readonly Entities _db = new Entities();
var entities = (from t in _db.table
where t.dateColumn.Date.Equals(DateTime.Today)
select t);
Like this?
SELECT ??? FROM YourTable WHERE DATE(dateTime) = DATE(NOW());
I think he means where the date part of the datetime field is today's date, correct?
In that case something like this would work:
SELECT CAST(yourdatecol AS DATE) FROM thetable WHERE CAST(yourdatecol AS date) = CURDATE();

Quick linq count question

I have the following query that returns the login count per day from a given date.
var sot = from uts in DataContext.UserTrackingStatistics
let startDate = new DateTime(2009, 10, 01)
where uts.LastLogin >= startDate
group uts by uts.LastLogin.Date into myGroup
orderby myGroup.Key.Date
select new { Count = myGroup.Count() , myGroup.Key.Date};
I would like this to say the count was 0 for a given day rather than not return anything. How could I do that within this query?
You can't do it just with LINQ-to-SQL, as you'd have to use a union on your query with data that doesn't actually exist, which LINQ-to-SQL can't do.
To do this, you'll need to fill in the gaps client-side. I'm not in front of VS at the moment, but a general approach would be this:
Define your date range (since you mention no end date in your code and we're talking about login date, I'm assuming that the end date would be the current date.
Use Enumerable.Range to create a list of numbers ranging from 0 to the number of days within your date range, then use Select to transform that list into a list of dates. Select your results using an anonymous type and use the same properties as your L2S statement; this way, the compiler will reuse the same type
Combine your lists together using an outer join (not the most obvious syntax in LINQ, unfortunately) on the Date property
Order your results by date
This will now show 0 for the gaps.
I'll try to post a code sample below, but note that I can't compile where I am, so it may require tweaking.
var allDates = Enumerable.Range(0, (DateTime.Today - startDate).TotalDays)
.Select(i => new { Count = 0, Date = startDate.AddDays(i) });
var fullResults = from d in allDates
join r in results on d.Date == r.Date
from oj in r.DefaultIfEmpty()
select new { Count = oj == null ? 0 : oj.Count, Date = d.Date };

Format DateTime in an EF query

I have a database table that holds information for received files. One of the columns is a DateTime that specifies when the file was received. I need to get a distinct list of months with the year (MM/YYYY) for files received. I need to get it out of this table. There can be thousands of records in this table so the way I have done it, in Oracle, is in my select statement I format the datetime as MM/YYYY and do a sort desc with a distinct clause on it. This give me a list of just the months that a file was received. Very fast and efficient.
Now I need to do this using EFv4....here's the query I used in Oracle. Anyone know how I can translate it using one of EFs ways of querying?
select distinct
to_char( i.date_received, 'MMYYYY')) MonthAndYear
from table1
order by MonthAndYear desc
Well, don't do it like Oracle. Do it like LINQ.
var q = (from i in Context.Table1
select new
{
Month = i.date_received.Month,
Year = i.date_received.Year
}).Distinct();
To get a DateTime out:
var r = q.AsEnumerable().Select(d => new DateTime(d.Year, d.Month, 1));

Categories