How to select hour in priority - c#

I'm using C# and SQL Server 2008 R2.
I have hour data like this:
Client_ID TheHour HourMin HourMAx
53026 09:00 7 9
53026 12:00 10 12
53026 15:00 13 15
53026 18:00 16 19
I will put TheHour into my combobox, that depends on computer hour.
When the computer hour is 10:00 then the value of my combobox:
12:00
15:00
18:00
09:00
My linq is :
int The_Hour = DateTime.Now.Hour;
var query = from o in oEntite_T.LS_CLIENTHORRAIRE
where o.CLIENT_ID == CLIENT_ID &&
The_Hour >= o.HEURE_MIN && The_Hour <= o.HEURE_MAX
select o;
LesListe = query.ToList();
It return only 1 value, which is 12:00.
That meant my combobox will select hour that depend on computer hour, but it leave the possibility for the user to select another hour.

Here is a working example in LINQPad, I also added a flag to indicate selected value.:
void Main()
{
var LS_CLIENTHORRAIREs = new List<LS_CLIENTHORRAIRE>
{
new LS_CLIENTHORRAIRE{TheHour="09:00",HourMin=7,HourMAx=9},
new LS_CLIENTHORRAIRE{TheHour="12:00",HourMin=10,HourMAx=12},
new LS_CLIENTHORRAIRE{TheHour="15:00",HourMin=13,HourMAx=15},
new LS_CLIENTHORRAIRE{TheHour="18:00",HourMin=16,HourMAx=19}
};
LS_CLIENTHORRAIREs.Dump();
int The_Hour = 10;
var query = from o in LS_CLIENTHORRAIREs
select new {o.TheHour,o.HourMin,o.HourMAx,selected = The_Hour >= o.HourMin && The_Hour <= o.HourMAx}
;
query.OrderBy (q => q.HourMAx>The_Hour ? 0 : 1).ThenBy (q => q.HourMAx).Dump();
}
public class LS_CLIENTHORRAIRE
{
public string TheHour{get;set;}
public int HourMin{get;set;}
public int HourMAx{get;set;}
}
Results

So, basically, you don't want to filter the list, you want to sort it, right?
First, you want to sort it by
whether the MaxHour is in the past
and then by
TheHour itself.
Example: Let's assume it is 10:00:
Client_ID TheHour HourMin HourMax MaxHourIsInThePast
53026 09:00 7 9 x
53026 12:00 10 12
53026 15:00 13 15
53026 18:00 16 19
Now you return a list that orders first by MaxHourIsInThePast (first those without x and then those with x) and then by TheHour.
Implementation is left as an exercise. Hint: You will need the LINQ order by keyword, and an expression similar to (o.HourMax < currentHour ? 2 : 1) will come in handy.

Let assume the computer hour is 10.
Then: your condition would be: HourMin <= 10 && HoureMax >= 10.
The first condition would return row 1 and 2. The second one would return row 2. The intersect will return only the second row, which is 12:00.
If you want to get all rows, just remove these conditions.

Related

how to get records between particular time using linq query in entity framework

i want to fetch records between time 8 pm to 6 am . how to write where clause to get the records between 8 pm and 6 am only.
Code
model = model.OrderByDescending(x => DateTime.Parse(x.UpdatedTime)).Where(x=>x.status=="UP").Take(100).ToList();
sample data
1 39 6/28/2017 12:08:43 PM UP
2 39 6/28/2017 12:04:18 PM UP
3 39 6/28/2017 11:49:45 AM UP
data type
public string UpdatedTime { get; set; }
controller
binModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
model = model.Where(x=> {
var timeOfDay = DateTime.Parse(x.UpdatedTime).TimeOfDay;
return x.status=="UP" &&
(timeOfDay.TotalHours >= 20 || timeOfDay.TotalHours < 6);
})
.OrderByDescending(x => DateTime.Parse(x.UpdatedTime)).Take(100).ToList();
should verify that the time is on or after 8pm, and prior to 6am.
Check the DateTime.Hour is more than 8pm or less that 6 AM
model = model.OrderByDescending(x => DateTime.Parse(x.UpdatedTime)).Where(x=>x.status=="UP" && (UpdatedTime.Hour > 20 || UpdatedTime.Hour < 6)).Take(100).ToList();

SQL to LINQ - Getting Wrong Results

If a user selects 07-07-2016, I want to count how many times billdays > 30 for that billdate month, for the past 12 months.
Query is this:
select COUNT(*) as 'BillsOver30' from pssuite_web.pujhaccd
where billdays>30 and DATEDIFF(month,'07-07-2016', GETDATE()) <= 13
Group By Month(billdate)
Result is this:
1784 (July)
1509 (June)
2986 (May)
2196 (etc)
5853
3994
1753
1954
869
1932
629
1673
LINQ query is:
DateStart = '07-07-2016' (from a textbox on view)
DateTime earliestDate = objdate1.DateStart.Value.AddMonths(-13);
var custQuery9 = (from m in DataContext.pujhaccds
where m.billdays > 30 &&
m.billdate >= earliestDate &&
m.billdate <= objdate1.DateStart
group m by m.billdate.Value.Month into p
select new Date1()
{
theMonth = p.Key,
theCount = p.Count()
});
Results are:
Month Count
1 1029
2 1018
3 1972
4 1519
5 2657
6 2019
7 1206
8 1023
9 761
10 1620
11 354
12 931
You can see that the LINQ query is way off.
Doesn't matter what date I put in, the result always stays the same. Rather than 12 months from starting date.
I must be writing it wrong, thanks.

C# LINQ query to use previous result if empty

I am having a datatable that is populated from an Access DB. The result looks like
Month | Sum
--------------
1 | 1464
2 | 1716
3 | 2125
4 | 2271
5 | 2451
6 | 2583
7 | 2671
9 | 2823
10 | 2975
You are right - nothing for august!
What I want is, that for august the same value as for july is used.
Currently I am using this LINQ query to add the data to a linechart:
for (int i = 1; i <= System.DateTime.Now.Month; i++)
{
var numbers = (from p in dTable.AsEnumerable()
where p.Field<int>("M") >= i
select p).First();
series2.Points.Add(new DataPoint { AxisLabel = i.ToString(), YValues = new double[] { Convert.ToDouble(numbers["Sum"]) } });
}
The chart is shown, but for august the september value is used. I assume it is something very basic that I am doing wrong but I simply canĀ“t figure it out.
Thanks in advance!
You are requesting all the months greater than the current month.
where p.Field<int>("M") >= i
So for August (8), your are retrieving September and greater (9, 10, 11, 12), not July (7).
You have to invert your constraint, and order by descending month:
var numbers = (from p in dTable.AsEnumerable()
where p.Field<int>("M") <= i
select p)
.OrderByDesc(p => p.Month)
.First();
You have to invert your logic:
var numbers = (from p in dTable.AsEnumerable()
where p.Field<int>("M") <= i
select p).Last();
It goes without saying that this doesn't work when there is no previous month.
UPDATE:
the above asumes that the table you are reading from is ordered. If that is not the case, you have to order yourself (as mentioned by Cyril Gandon):
var numbers = (from p in dTable.AsEnumerable()
where p.Field<int>("M") <= i
orderby p.Field<int>("M") descending
select p).First();

LINQ Query to get values from database at specified time intervals

I want to fetch values from database with specific intervals in C# and need a LINQ query for that.
This is what my database looks like
Id SensorId Value CreatedOn
1 8 33.5 15-11-2012 5:48 PM
2 5 49.2 15-11-2012 5:48 PM
3 8 33.2 15-11-2012 5:49 PM
4 5 48.5 15-11-2012 5:49 PM
5 8 31.8 15-11-2012 5:50 PM
6 5 42.5 15-11-2012 5:50 PM
7 8 36.5 15-11-2012 5:51 PM
8 5 46.5 15-11-2012 5:51 PM
9 8 39.2 15-11-2012 5:52 PM
10 5 44.4 15-11-2012 5:52 PM
11 8 36.5 15-11-2012 5:53 PM
12 5 46.5 15-11-2012 5:53 PM
13 8 39.2 15-11-2012 5:54 PM
14 5 44.4 15-11-2012 5:54 PM
.. . .... ...................
The interval is in minutes.
So, if the interval is 10 minutes, then we need the values at 5:48, 5:58, 6:08 and so on...
This is what I have tried
while (startDateTime <= endDateTime)
{
var fetchIndex =
fullValues.Where(
item =>
item.CreatedOn >= startDateTime &&
item.CreatedOn < startDateTime.AddMinutes(1)).Select(
item => item.FetchIndex).FirstOrDefault();
if (fetchIndex != 0)
{
var temp = fullValues.Where(item => item.FetchIndex == fetchIndex).ToList();
result = result.Union(temp);
}
startDateTime = startDateTime.AddMinutes(interval);
}
Since the while loop iterates through the table, it takes a lot of time to get these values.
Is there any way of getting the data in a single query?
from x in table
where x.CreatedOn >= startDateTime &&
x.CreatedOn <= endDateTime &&
(x.CreatedOn.Minute % 10) == 0
select x
this will give you 1:00,1:10,1:20
The 10 represents your interval and 0 is your offset.
Following approach creates a list requiredTimes which holds all of the relevant datetimes between startDateTime and endDateTime (datetimes in 10 minute intervals between start and end datetimes).
After such list is created the fullValues is inner joined on it. The result is an IEnumerable with datetimes from fullValues that satisfy the interval condition. It should work fast since creating such list is quick and the Join method is an inner join which should also work fast, try it:
DateTime startDateTime = DateTime.Parse("15-11-2012 5:48 PM");
DateTime endDateTime = DateTime.Parse("16-11-2012 5:58 PM");
List<DateTime> requiredTimes = new List<DateTime>();
DateTime dt = startDateTime;
requiredTimes.Add(dt);
while (dt <= endDateTime)
{
dt = dt.AddMinutes(10);
requiredTimes.Add(dt);
}
var result = fullValues.Join(
requiredTimes,
fv => fv.CreatedOn,
rt => rt,
(fv, rt) => fv);

Complex LINQ to SQL Query with dates

I'm building a query with LINQ to SQL in my C# project, but I have some problems with it...
What I want to do, is select the 4 lasts days that are like today (For example, a Friday), so if we're on Friday 28, I want to query for: Friday 21, 14, 7... The last four Fridays but NOT today.
This is easy, I've done that but here's the complex part, I want to not query the exceptions I set, for example End of month, which are from 28th to 1st day of each month, so let's say i want to query this (october, fridays):
Today is Friday 26, I want to query:
19, 12, 5 and September 28th (the fourth friday from now), but as I said, 28th is end of month, so i need to return September 21th which is the last friday and it is not end of month... I have the same issues with holidays, but I think if I can handle end of months, I can do with them...
i hope I've explained good for you to understand what I want... Here's my query, which is working but can't handle exceptions. (the field b.day is the Id for each days, 8 means end of month, and 7 holiday)
var values =
from b in dc.MyTable
where // This means end of month
b.day != 8
// This triggers to query last 4 days
&& b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-28)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-21)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-14)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-7)
orderby b.id descending
group b.valor by b.hora_id into hg
orderby hg.Key descending
select new
{
Key = hg.Key,
Max avg = System.Convert.ToInt32(hg.Average() + ((hg.Average() * intOkMas) / 100)),
Min avg = System.Convert.ToInt32(hg.Average() - ((hg.Average() * intOkMenos) / 100))
};
You should prepare the list of days you'd like retrieve before trying to query:
// Get the last four days excluding today on the same weekday
var days = Enumerable.Range(1, 4).Select(i => DateTime.Today.AddDays(i * -7));
Then remove any days you don't want:
// Remove those pesky end-of-month days
days = days.Where(d => d.Day < 28 && d.Day > 1);
When you're done preparing the list of days you want to retrieve, only then should you perform your query:
from b in dc.MyTable
where days.Contains(b.date) // Translated to SQL: date IN (...)
...
EDIT: As you mentioned in your comment, you want a total of four days even after any filtering you perform. So simply generate more days and take the first four:
var days = Enumerable.Range(1, int.MaxValue - 1)
.Select(i => DateTime.Today.AddDays(i * -7))
.Where(d => d.Day < 28 && d.Day > 1)
.Take(4);
Due to the way LINQ (and in general, enumerators) work, only four days plus any skipped days will be calculated.
Building on Allon Guralnek's answer, I'd modify it slightly:
First, build an infinite date generator:
public IEnumerable<DateTime> GetDaysLikeMe(DateTime currentDate)
{
DateTime temp = currentDate;
while(true)
{
temp = temp.AddDays(-7);
yield return temp;
}
}
Then you can use deferred execution to your advantage by limiting to only dates that meet your additional criteria:
GetDaysLikeMe(DateTime.Now).Where(dt => /* dt meets my criteria */).Take(4)
Then you can use this list that was generated to query in your LINQ to SQL like Allon Guralnek suggested above:
from b in dc.MyTable
where days.Contains(b.date) // Translated to SQL: date IN (...)
...
This has the benefit of you being able to specify additional predicates for what are acceptable dates and still get at least 4 dates back. Just be sure to put some bounds checking on the infinite date generator in case one of your predicates always returns false for whatever reason (which means the generator will never exit).
IE: while(temp > currentDate.AddYears(-1))
I would highly suggest writing your exception code (last friday of the month) after retrieving your rows, as this logic seems to be too complicated for a LINQ statement. Instead of retrieving the last 4 days, retrieve the last 5. Remove any that are the last Friday of each respective months. If you still have 5 rows, remove the last one.
Update
var values1 =
from b in dc.MyTable
where // This means end of month
b.day != 8
// This triggers to query last 4 days
&& b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-28)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-21)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-14)
|| b.date == Convert.ToDateTime(last.ToString("dd/MM/yyy")).AddDays(-7)
orderby b.id descending
select b;
//Do stuff with values
var values2 = from b in values2
group b.valor by b.hora_id into hg
orderby hg.Key descending
select new
{
Key = hg.Key,
Max avg = System.Convert.ToInt32(hg.Average() + ((hg.Average() * intOkMas) / 100)),
Min avg = System.Convert.ToInt32(hg.Average() - ((hg.Average() * intOkMenos) / 100))
};

Categories

Resources