Reputation: 2741
I am trying to create a LINQ query that will filter out data with criteria from two different columns.
I am trying to get data between two dates from Time_Data_1
column only when a specific string value is met from Section_Data
column,
ie,
Between 2016/5/15
and 2016/6/16
when SelectedOption = Something
This is what I have, which is not working.
DataGridOne.DataContext = sql.Time_TBLs.Where(item =>
item.Time_Data_1 < new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, 15) &&
item.Time_Data_1 > new DateTime(DateTime.Now.Year, DateTime.Now.Month, 16) &&
item.Section_Data == SelectedOption);
This query below works for the single criteria of getting data between two dates. But it picks up every bit of data between those dates.
Column1.DataContext = sql.Time_TBLs.Where(item =>
item.Time_Data_1 < new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, 15) &&
item.Time_Data_1 > new DateTime(DateTime.Now.Year, DateTime.Now.Month, 16)
How do add a second criteria to the query?
EDIT: Typo, supposed to && when I put &
Upvotes: 0
Views: 301
Reputation: 581
Conditional statement is wrong.
You want to filter between two dates i.e between 2016/05/15
and 2016/06/16
but your condition says you want less then 2016/05/15
and greater than 2016/06/16
.
Your code should be like this.
DataGridOne.DataContext = sql.Time_TBLs.Where(item =>
item.Time_Data_1 > new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, 15)
&& item.Time_Data_1 < new DateTime(DateTime.Now.Year, DateTime.Now.Month, 16)
&& item.Section_Data == SelectedOption);
Upvotes: 1
Reputation: 613
Any specific error/issue you are getting?
As far as code goes all I would say is possibly BODMAS and bitwise & operator. Read more on & on Usage & versus &&
Meanwhile does this code work for you?
DataGridOne.DataContext = sql.Time_TBLs.Where(item =>
(item.Time_Data_1 < new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, 15) &&
item.Time_Data_1 > new DateTime(DateTime.Now.Year, DateTime.Now.Month, 16)) &&
item.Section_Data == SelectedOption);
PS : When working with pure DateTime, i find it easier to do 17 instead of 16 for dates. As all times default to 00:00:0000, and hence if you have data like 16/06/2016 07:05:0000 it would not be fetched back from the query that checks for DateTime.Day of 16.
Upvotes: 1