How to iterate date in for loop? - c#

I have some values.
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
Shift Group=S1(this group contain two shift id 1 and 2)
I want to run the shift for 6 days. but after each 2 days Shift id 1 rotate to shift id 2 and again after two days shift id 2 rotate to shift id 1 and so on...
My output should be like
04/03/2015=1
05/03/2015=1
06/03/2015=2
07/03/2015=2
08/03/2015=1
09/03/2015=1
I am getting shift id through a foreach loop. I tried like below mentioned way but not getting a proper resul. Please help me solve this issue
SqlCommand cmd2 = new SqlCommand("select ShiftID from ShiftGroup where
ShiftName='" + ide + "'", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataSet ds4 = new DataSet();
var rows2 = ds4.Tables[0].Rows;
if (ds4.Tables[0].Rows.Count > 0)
{
foreach (DataRow row2 in rows2)
{
string shiftname = Convert.ToString(row2["ShiftID"]);
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
DateTime rotation= date.AddDays(rotationday);//
DateTime totaldate = date.AddDays(workingdays);
for (DateTime rotation = date; rotation <= totaldate; rotation = rotation.AddDays(1))//total working days
{
//to check rotation date
if (rotation <= totaldate )
{
allocation.shiftallocation( rotation, shiftid);
}
}
}
I am stucked with this from last day, anybody help me . No need of consider my for loop, kindly provide a for loop which generate the above mentioned output

You can try this,
DateTime date=DateTime.ParseExact("04/03/2015","dd/MM/yyyy",CultureInfo.InvariantCulture);
DateTime totaldate = date.AddDays(6);
for (int i=0; date <= totaldate; date = date.AddDays(1),i++)//total working days
{
if((i/2)%2==0)
Console.WriteLine(date+" "+1);
else
Console.WriteLine(date+" "+2);
}

Don't use dates at loop cycle, use abstract indicies. You can really abstract from concrete numbers and use only variables for managing result. So you can easily change rotationDays count and even workshifts labels array without changing cycle.
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 15;
var rotationDays = 2;
var workshifts = new[] { "S1", "S2" };
var currentWorkshiftIndex = 0;
for (int dayIndex = 0; dayIndex <= totalWorkingDays; dayIndex++) {
if (dayIndex != 0 && dayIndex % rotationDays == 0) currentWorkshiftIndex = (currentWorkshiftIndex + 1) % workshifts.Length;
Console.WriteLine(date.AddDays(dayIndex) + " " + workshifts[currentWorkshiftIndex]);
}

var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
var rotationId = 1;
var rotationCounter = 1;
for (DateTime rotation = date;
rotation <= date.AddDays(totalWorkingDays);
rotation = rotation.AddDays(1))
{
Console.WriteLine(rotation + " " + rotationId);
if (rotationCounter++ == 2)
{
rotationCounter = 1;
rotationId = 3 - rotationId;
}
}
Or, with a linq query
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
foreach (var d in Enumerable.Range(0, totalWorkingDays)
.Select((i, index) => date.AddDays(i) +
(((int)(index / rotationDays)) % 2 == 1 ? " 2" : " 1")))
{
Console.WriteLine(d);
}

According to your comment for the 5 working days a week, I wrote this:
var start = new DateTime(2015, 04, 03);
var working_day_count = 6;
var rotation_interval = 2;
var shifts = new List<int> { 1, 2 };
var rotation_count = 1;
var shift_index = 0;
for (var i = 0; i < working_day_count; i++) {
while ((start.DayOfWeek == DayOfWeek.Saturday) ||
(start.DayOfWeek == DayOfWeek.Sunday)) {
start = start.AddDays(1);
}
Console.WriteLine(start.ToString() + " = " + shifts[shift_index].ToString());
start = start.AddDays(1);
rotation_count++;
if (rotation_count > rotation_interval) {
rotation_count = 1;
shift_index++;
if (shift_index >= shifts.Count) {
shift_index = 0;
}
}
}
Just change the values of the first four varibales as you like.
I tried to make it easy to understand instead of performant or compact.

A generic solution with holidays taken into account.
int totalDays = 10;
int rotationDays = 3;
int[] shifts = new[] { 1, 2 };
string startDate = "04/03/2015";
var holidays = new List<DayOfWeek>(new[] { DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Tuesday });
var shiftAllocations = new Dictionary<DateTime, int>();
int currentShiftIndex = 0;
DateTime current = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for (int i = 0; i < totalDays; i += rotationDays)
{
var currentShiftId = shifts[currentShiftIndex];
// For each day from the current day till the number of shift rotation days, allocate the shift.
for (int j = 0; j < rotationDays;)
{
// If the current day is a holiday, move to the next day by incrementing i.
if (holidays.Contains(current.AddDays(i + j).DayOfWeek))
{
i++;
continue;
}
shiftAllocations.Add(current.AddDays(i + j), currentShiftId);
j++;
}
// Increase the shift index if the value is within the bounds. If not reset the index to the beginning
if ((currentShiftIndex + 1) >= shifts.Length)
currentShiftIndex = 0;
else
currentShiftIndex++;
}
foreach (var kvp in shiftAllocations)
{
Console.WriteLine(kvp.Key.ToString("dd/MM/yyyy") + ":" + kvp.Value);
}

Related

Why List is not filled with n number of records and x number of dates, 2 differen records per date, until all dates are used? C#

int dateOffset = 0;
DateTimeOffset currentDate = DateTimeOffset.Now;
do
{
int sameDayCount = 0;
do
{
for (int record = 0; record < List.Count; record++)
{
Client client = new Client();
client.Name = List[record].Name;
client.Date = currentDate.AddDays(dateOffset);
List2.Add(client);
sameDayCount += 1;
}
} while (sameDayCount < 2);
dateOffset += 1;
} while (dateOffset < 30);
The above is the code I wrote thanks to my modest knowledge about and experience with the C# language.
As you may expect it does not work as expected.
I need to populate the List2 with data from the List and additional element -DateTime.
Basically I want to schedule the names of clients for 30 days, two per day.
In the code i wrote I was hoping that do{} while (sameDayCount < 2); will work, but the sameDayCount += 1; is inside the for loop and do{} while actually waits for the for loop to finish (when it reaches record == List.Count). Anyway, the for loop will start over from record = 0 and I need it to go on from the last point it was left out when reached 2 records per day.
Any idea how I could resolve the problem?
So there are:
a List with finite number of records (Client's names)
30 days to be asssigned along with records
there must be two different records for each date
list with records must be re-read from the place it was left off
when the list is fully iterated(b=List.Count), it starts over again from b=0
the whole loop ends when 30th day is reached.
in few words, seen that my question is not clear at all.
Lets say first list contains 5 clients(the number may vary).
I want to populate second list with those 5 clients + 7 days.
I want the second list to become like:
day1 - client1, client2
day2 - client3, client4
day3 - client5, client1
day4 - client2, client3
day5 - client4, client5
day6 - client1, client2
day7 - client3, client4
You can do it with one for-loop only by stepping by 2
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < 60; i += 2) {
AddClient(i, currentDate);
if (i + 1 < List.Count) {
AddClient(i + 1, currentDate);
}
currentDate = currentDate.AddDays(1);
}
void AddClient(int clientIndex, DateTime dateTime)
{
var client = new Client {
Name = List[clientIndex].Name,
Date = dateTime
};
List2.Add(client);
}
You don't need a loop for the 30 days. Just loop until the clients run out (i < List.Count) or you have scheduled 60 clients, i.e., until you have reached 30 days. In case the number of clients is odd, i + 1 < List.Count makes sure that you don't exceed the list.
If you want to be more flexible with the count of clients per day, use 2 loops. One which loops through the source list in steps of ClientsPerDay and one which loops the ClientsPerDay:
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
As an alternative you could calculate the loop count in advance with
int clientCount = Math.Min(List.Count, ClientsPerDay * 30);
for (int i = 0; i < clientCount; i += ClientsPerDay) {
...
}
Starting over
You have changed the question in the meantime. If you want start over with the clients if the number of days is not reached but the clients run out, you can use the modulo operator (%) to make the indexes start over.
const int ClientsPerDay = 2, NumDays = 30;
DateTime date = DateTime.Now.Date;
for (int i = 0; i < ClientsPerDay * NumDays; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = (i + j) % List.Count; // clientIndex = [0 .. List.Count - 1]
var client = new Client {
Name = List[clientIndex].Name,
Date = date
};
List2.Add(client);
}
date = date.AddDays(1);
}
See also: Circular array on GeeksforGeeks.
Well, I think I understand the question - so here is what I suggest you do:
First, loop over the Client's names only once.
Inside that loop, nest a second loop, counting from 0 to 59.
In that loop, add the clients to the target list, adding the inner loop counter % 30 days to the current datetime value:
// meaningful names - i is kinda "defacto standard" as a for loop counter
for (int i = 0; i < List.Count; i++)
{
// using j for nesting loops is also kinda "defacto standard"
for(int j = 0; j < 60; j++)
{
// you already know it's a client, use var!
var client = new Client();
client.Name = List[record].Name;
client.Date = currentDate.AddDays(j % 30);
List2.Add(client);
}
}
Of course, there are more advanced solutions for this kind of thing like using linq - but I'm not sure I'm comfortable suggesting linq to a c# beginner - I think it's better to start with the basics and work your way up to advanced stuff.
as Olivier Jacot-Descombes suggested:
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
But this goes until the List.Count is reached. So it populates the list only until the clients are all used.
Instead, I am looking for a solution that will loop the same Clients until 30 day limit is reached.
Something like this:
do
{
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
} while (currentDate < currentdate.AddDays(30));
But my Do simply repeats the job instead of going on with dates.
Something like this, I guess? All dates in UTC - it's easier to work with canonical datetimes rather than using those crappy looking offsets. You can always convert them to locale when you need to show them in terminal, so there is no reason to work with them up until final point.
public static void Main(string[] args)
{
var currentDate = DateTime.UtcNow;
var daysInMonth = DateTime.DaysInMonth;
var repeats = 2;
for(var i = 0; i < daysInMonth;i++)
{
foreach(var item in List)
{
for(var r = 0; r < repeats;r++)
{
var client = new Client
{
Name = item.Name,
Date = currentDate.AddDays(i)
};
List2.Add(client);
}
}
}
}
PS: Question is really bad, I didn't understand a thing.

Adding multiple times in (HH.mm)

data in sqlserver.
calling it in gridview
how do i add all the time in the column, i have 4 columns to calculate for different total time.
for example :
time 1 = 256.20 (HH.mm)
time 2 = 257.41 (HH.mm)
time 3 = 114.50 (HH.mm)
time 4 = 371.20 (HH.mm)
total = 1000.11 (HH.mm)
the total will keep on increasing but the format must be hours and minutes.
i added 2 time for the time 1 from above using string split
doing it in C#.net
thanking you in advance.
thank you very much #CodingYoshi
> //string time1 = TextBox1.Text;
//string time2 = TextBox2.Text;
//string[] part1 = time1.Split('.');
//int h1 = int.Parse(part1[0]);
//int m1 = int.Parse(part1[1]);
//string[] part2 = time2.Split('.');
//int h2 = int.Parse(part2[0]);
//int m2 = int.Parse(part2[1]);
//int totalHours = h1 + h2;
//int totalMinutes = m1 + m2;
//if (totalMinutes >= 60)
//{
// totalHours = totalHours + 1;
// totalMinutes = totalMinutes % 60;
//}
var times = new List<string>
{
TextBox1.Text,TextBox2.Text
};
TimeSpan total = new TimeSpan();
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalHours = (int)total.TotalHours;
var totalMinutes = total.Minutes;
TextBox3.Text = totalHours.ToString() + "." + totalMinutes.ToString();
from gridview
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from totalHours";
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
TimeSpan total = new TimeSpan();
var times = new List<string> ();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
times.Add((GridView1.Rows[i].Cells[0].Text));
}
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalHours = (int)total.TotalHours;
var totalMins = total.Minutes;
Label2.Text = totalHours.ToString() + "." + totalMins.ToString();
thank you again #CodingYoshi
Here I am adding 2 of them and you can do the rest:
var t1 = new TimeSpan(256, 20, 0);
var t2 = new TimeSpan(257, 41, 0);
var tTotal = t1.Add(t2).ToString(#"dd\.hh\:mm\:ss");
tTotal will display the days, hours, minutes and seconds of adding t1 and t2;
If you want to do them using a loop, you can do it like this:
var times = new List<string>
{
"256.20",
"257.41",
"114.50",
"371.20",
"1000.11"
};
TimeSpan total = new TimeSpan();
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalDisplay = total.ToString(#"dd\.hh\:mm\:ss");
If you want the total hours and minutes:
var totalHours = (int)total.TotalHours;
var totalMins = total.Minutes;

C# is there a faster way to get max diff between a date set than for loop

I have a list of dates in descending order e.g.
var dates = {date1, date2, date3};
Task is to find the maximum number of days between the dates.
What I have done so far is:
var maxDays = 0;
var previousDate = dates.First();
foreach (var thisDate in dates.Skip(0))
{
maxDays = Max(thisDate - previousDate, maxDays);
previousDate = thisDate;
}
This works fine until I get around 1000+ dates in a list.
Can you recommend any other ways?
Thanks
I would suggest a slightly different approach:
HashSet<TimeSpan> counts = new HashSet<TimeSpan>();
var previousDate = dates.First();
foreach (var thisDate in dates.Skip(1))
{
counts.Add(previousDate - thisDate);
previousDate = thisDate;
}
var max = counts.Max();
The idea is to not calculate the max for each iteration but rather collect the differences and then let the Max be a set operation.
Using a HashSet also reduces the number of [unique] differences that you will be checking.
I tested this with 200,000 dates and it took less than 300 milliseconds.
Assuming dates is a List<DateTime>, you can just run a loop that starts with the first element and goes until the second-to-last element. Then inside the loop, you compare the current element with the next one, and if the difference is greater than your current max, reset it:
double maxDays = 0;
for (int i = 0; i < dates.Count - 1; i++)
{
var diff = (dates[i + 1] - dates[i]).TotalDays;
if (diff > maxDays ) maxDays = diff;
}
Here's a benchmark test that shows it takes about 10 milliseconds to process 1 million items:
private static void Main()
{
var numDates = 1000000;
var dates = new List<DateTime>();
// initialize list with random dates
var rnd = new Random();
for (int i = 0; i < numDates; i++)
{
var day = rnd.Next(1, 29);
var month = rnd.Next(1, 13);
var year = rnd.Next(DateTime.MinValue.Year, DateTime.MaxValue.Year + 1);
dates.Add(new DateTime(year, month, day));
}
// Sort the list descending
dates = dates.OrderByDescending(d => d).ToList();
// find the two neighbors with the greatest distance
double maxDays = 0;
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < dates.Count - 1; i++)
{
var diff = (dates[i] - dates[i + 1]).TotalDays;
if (diff > maxDays) maxDays = diff;
}
sw.Stop();
// Display results
Console.WriteLine($"The greatest difference was {maxDays} days.");
Console.WriteLine($"The comparison of {dates.Count} items took {sw.ElapsedMilliseconds} milliseconds");
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output

Odd C# behavior

I'm a hobby programmer.
I tried to ask this question earlier on a very unstructured way (Sorry again), now I try to ask on the proper way.
I wrote the following code that seems to work unreliably.
The code was written like this for several reasons. I know it's messy but it should still work. To explain why I wrote it like this would mean that I need to explain several weeks' of work that is quite extensive. Please accept that this is at least the least worse option I could figure out. In the below sample I removed all sections of the code that are not needed to reproduce the error.
What this program does in a nutshell:
The purpose is to check a large number of parameter combinations for a program that receives streaming data. I simulate the original process to test parameter combinations.
First data is read from files that represents recorded streaming data.
Then the data is aggregated.
Then I build a list of parameters to test for.
Finally I run the code for each parameter combination in parallel.
Inside the parallel part I calculate a financial indicator called the bollinger bands. This is a moving average with adding +/- standard deviation. This means the upper line and the lower line should only be equal when variable bBandDelta = 0. However sometimes it happens that CandleList[slot, w][ctr].bollingerUp is equal to CandleList[slot, w][ctr].bollingerDown even when bBandDelta is not 0.
As a result I don't understand how can line 277 kick in. It seems that sometimes the program fails to write to the CandleList[slot, w][ctr]. However this should not be possible because (1) I lock the list and (2) I use ConcurrentBag. Could I have some help please?
Source files are here.
The code is:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Justfortest
{
class tick : IComparable<tick> //Data element to represent a tick
{
public string disp_name; //ticker ID
public DateTime? trd_date; //trade date
public TimeSpan? trdtim_1; //trade time
public decimal trdprc_1; //price
public int? trdvol_1; //tick volume
public int CompareTo(tick other)
{
if (this.trdprc_1 == other.trdprc_1)
{
return other.trdprc_1.CompareTo(this.trdprc_1); //Return the later item
}
return this.trdprc_1.CompareTo(other.trdprc_1); //Return the earlier item
}
}
class candle : IComparable<candle> //Data element to represent a candle and all chart data calculated on candle level
{
public int id = 0;
public DateTime? openDate;
public TimeSpan? openTime;
public DateTime? closeDate;
public TimeSpan? closeTime;
public decimal open = 0;
public decimal high = 0;
public decimal low = 0;
public decimal close = 0;
public int? volume = 0;
public decimal totalPrice = 0;
public decimal bollingerUp = 0; //Bollinger upper line
public decimal bollingerDown = 0; //Bollinger below line
public int CompareTo(candle other)
{
if (totalPrice == other.totalPrice)
{
return other.totalPrice.CompareTo(totalPrice); //Return the later item
}
return totalPrice.CompareTo(other.totalPrice); //Return the earlier item
}
}
class param : IComparable<param> //Data element represent a trade event signal
{
public int par1;
public int bollPar;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public decimal par7;
public decimal par8;
public decimal par9;
public decimal par10;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class programCLass
{
void myProgram()
{
Console.WriteLine("Hello");
Console.WindowWidth = 180;
string[] sources = new string[]
{
#"C:\test\source\sourceW1.csv",
#"C:\test\source\sourceW2.csv",
};
List<candle>[] sourceCandleList = new List<candle>[sources.Count()];
List<param> paramList = new List<param>(10000000);
var csvAnalyzer = new StringBuilder();
{
List<tick>[] updatelist = new List<tick>[sources.Count()];
Console.WriteLine("START LOAD");
for (var i = 0; i < sources.Count(); i++)
{
var file = sources[i];
updatelist[i] = new List<tick>();
// ---------- Read CSV file ----------
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
tick update = new tick();
update.disp_name = values[0].ToString();
update.trd_date = Convert.ToDateTime(values[1]);
update.trdtim_1 = TimeSpan.Parse(values[2]);
update.trdprc_1 = Convert.ToDecimal(values[3]);
update.trdvol_1 = Convert.ToInt32(values[4]);
updatelist[i].Add(update);
}
Console.WriteLine(i);
}
Console.WriteLine("END LOAD"); // All files are in the memory
// Aggreagate
Console.WriteLine("AGGREGATE START");
int tickAggr = 500;
for (var w = 0; w < sources.Count(); w++)
{
sourceCandleList[w] = new List<candle>();
List<tick> FuturesList = new List<tick>();
foreach (var update in updatelist[w])
{
tick t = new tick();
t.disp_name = update.disp_name.ToString();
t.trd_date = update.trd_date;
t.trdtim_1 = update.trdtim_1;
t.trdprc_1 = Convert.ToDecimal(update.trdprc_1);
t.trdvol_1 = update.trdvol_1;
// Add new tick to the list
FuturesList.Add(t);
if (FuturesList.Count == Math.Truncate(FuturesList.Count / (decimal)tickAggr) * tickAggr)
{
candle c = new candle();
c.openDate = FuturesList[FuturesList.Count - tickAggr].trd_date;
c.openTime = FuturesList[FuturesList.Count - tickAggr].trdtim_1;
c.closeDate = FuturesList.Last().trd_date;
c.closeTime = FuturesList.Last().trdtim_1;
c.open = FuturesList[FuturesList.Count - tickAggr].trdprc_1;
c.high = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Max().trdprc_1;
c.low = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Min().trdprc_1;
c.close = FuturesList.Last().trdprc_1;
c.volume = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Sum(tick => tick.trdvol_1);
c.totalPrice = (c.open + c.high + c.low + c.close) / 4;
sourceCandleList[w].Add(c);
if (sourceCandleList[w].Count == 1)
{
c.id = 0;
}
else
{
c.id = sourceCandleList[w][sourceCandleList[w].Count - 2].id + 1;
}
}
}
FuturesList.Clear();
}
Console.WriteLine("AGGREGATE END");
for (var i = 0; i < sources.Count(); i++)
{
updatelist[i].Clear();
}
}
Console.WriteLine("BUILD PARAMLIST");
for (int par1 = 8; par1 <= 20; par1 += 4) // parameter deployed
{
for (int bollPar = 10; bollPar <= 25; bollPar += 5) // parameter deployed
{
for (int par2 = 6; par2 <= 18; par2 += 4) // parameter deployed
{
for (int par3 = 14; par3 <= 20; par3 += 3) // parameter deployed
{
for (int par4 = 10; par4 <= 20; par4 += 5) // parameter deployed
{
for (int par5 = 4; par5 <= 10; par5 += 2) // parameter deployed
{
for (int par6 = 5; par6 <= 30; par6 += 5)
{
for (decimal par7 = 1.0005M; par7 <= 1.002M; par7 += 0.0005M)
{
for (decimal par8 = 1.002M; par8 <= 1.0048M; par8 += 0.0007M)
{
for (decimal par9 = 0.2M; par9 <= 0.5M; par9 += 0.1M)
{
for (decimal par10 = 0.5M; par10 <= 2; par10 += 0.5M)
{
param p = new param();
p.par1 = par1;
p.bollPar = bollPar;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("END BUILD PARAMLIST, scenarios to test:{0}", paramList.Count);
var sourceCount = sources.Count();
sources = null;
Console.WriteLine("Start building pools");
int maxThreads = 64;
ConcurrentBag<int> pool = new ConcurrentBag<int>();
List<candle>[,] CandleList = new List<candle>[maxThreads, sourceCount];
for (int i = 0; i <= maxThreads - 1; i++)
{
pool.Add(i);
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[i, w] = sourceCandleList[w].ConvertAll(p => p);
}
}
Console.WriteLine("End building pools");
int pItemsProcessed = 0;
Parallel.ForEach(paramList,
new ParallelOptions { MaxDegreeOfParallelism = maxThreads },
p =>
{
int slot = 1000;
while (!pool.TryTake(out slot));
var bollPar = p.bollPar;
decimal bollingerMiddle = 0;
double bBandDeltaX = 0;
for (var w = 0; w < sourceCount; w++)
{
lock (CandleList[slot, w])
{
for (var ctr = 0; ctr < CandleList[slot, w].Count; ctr++)
{
CandleList[slot, w][ctr].bollingerUp = 0; //Bollinger upper line
CandleList[slot, w][ctr].bollingerDown = 0; //Bollinger below line
//Bollinger Bands Calculation
if (ctr + 1 >= bollPar)
{
bollingerMiddle = 0;
bBandDeltaX = 0;
for (int i = 0; i <= bollPar - 1; i++)
{
bollingerMiddle = bollingerMiddle + CandleList[slot, w][ctr - i].totalPrice;
}
bollingerMiddle = bollingerMiddle / bollPar; //average
for (int i = 0; i <= bollPar - 1; i++)
{
bBandDeltaX = bBandDeltaX + (double)Math.Pow(System.Convert.ToDouble(CandleList[slot, w][ctr - i].totalPrice) - System.Convert.ToDouble(bollingerMiddle), 2);
}
bBandDeltaX = bBandDeltaX / bollPar;
decimal bBandDelta = (decimal)Math.Sqrt(System.Convert.ToDouble(bBandDeltaX));
CandleList[slot, w][ctr].bollingerUp = bollingerMiddle + 2 * bBandDelta;
CandleList[slot, w][ctr].bollingerDown = bollingerMiddle - 2 * bBandDelta;
if (CandleList[slot, w][ctr].bollingerUp == CandleList[slot, w][ctr].bollingerDown)
{
Console.WriteLine("?! Items processed=" + pItemsProcessed + " bollPar=" + bollPar + " ctr=" + ctr + " bollingerMiddle=" + bollingerMiddle + " bBandDeltaX=" + bBandDeltaX + " bBandDelta=" + bBandDelta + " bollingerUp=" + CandleList[slot, w][ctr].bollingerUp + " bollingerDown=" + CandleList[slot, w][ctr].bollingerDown);
}
}
// REMOVED Further calculations happen here
}
// REMOVED Some evaluations happen here
}
}
// REMOVED Some more evaluations happen here
Interlocked.Increment(ref pItemsProcessed);
pool.Add(slot);
});
}
static void Main(string[] args)
{
var P = new programCLass();
P.myProgram();
}
}
}

Wpf C# DateTime Database

I have two tables in my database, energyinfo (t1) and enerfyinfometers (t2).
I have a start and stop time in t1 like 500 min difference.
I want to add the time in between t1 (start and stop) for every one minute in t2.
Here's my code. it takes a lot of time to run and t1 entries is happening but fails to do t2.
if (dbContext == null)
{
dbContext = Context.Create("d:\\temp\\new.sdf", "");
var start = DateTime.Now;
DateTime time = DateTime.Now;
DateTime time2 = DateTime.Now;
// time = time + TimeSpan.FromMinutes(30);
time2 = time2 + TimeSpan.FromMinutes(1);
Random rnd = new Random();
double Counter = 50;
var stop = start.AddMinutes(15);
double value2 =36;
for (int i = 1; i < 36; i++)
{
Counter = Counter + 0.5;
double value3 = rnd.Next (2,12) +0.5;
double value4 = value3 / 2;
double value = rnd.Next(50) + 0.5;
value2 += (value / 60);
double roundedValue = Math.Ceiling(value2) + 1;
int LMH = rnd.Next(0, 3);
dbContext.EnergyInfo.Add(new EnergyInfo()
{ EId = i,
Timestamp = time, type = LMH,
startTime = start, stopTime = stop,
demandCharge = value3,
threshHold = 70,
normalCharge = value4,
peakDuration = 900 });
dbContext.SaveChanges();
for (var x = start; x < stop; x.AddMinutes(1))
{
var ob = new EnergyMeterInfo() { Timestamp = x, MeterId = 5,
powerConsumptionKW = Counter,
cumlativePwrConsumption = roundedValue,
EnergyInfoId = i };
using (dbContext.Database.BeginTransaction())
{
dbContext.EnergyMeterInfo.Add(ob);
}
}
start = stop;
stop = start.AddMinutes(500);
dbContext.SaveChanges();
}
}
MessageBox.Show(dbContext.EnergyInfo.Count() + " Records found !" + dbContext.EnergyMeterInfo.Count() + " found");
x.AddMinutes(1) does not change the value of x. Instead it returns a new DateTime instance, which you should then assign to x.
The loop should therefore look like this:
for (var x = start; x < stop; x = x.AddMinutes(1))
{
...
}

Categories