I have already asked a different question regarding Sorting Date Time and got help from another user to pass my values. I am using a for loop like below, but definitely am wrong here because the code brings the value one by one rather than sorting.
public class Break
{
public DateTime MealStart { get; set; }
public DateTime MealEnd { get; set; }
}
my main class
IList<DateTime> starts = new List<DateTime>();
IList<DateTime> ends = new List<DateTime>();
DateTime breakStart1 = new DateTime(2012, 02, 15, 12, 30, 00); // 15/02/12 12.30PM
DateTime breakEnd1 = new DateTime(2012, 02, 15, 13, 30, 00); // 15/02/12 01.30PM
DateTime breakStart2 = new DateTime(2012, 02, 15, 11, 00, 00); // 15/02/12 11.00AM
DateTime breakEnd2 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakStart3 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakEnd3 = new DateTime(2012, 02, 15, 01, 00, 00); // 15/02/12 01.00PM
starts.Add(breakStart1);
starts.Add(breakStart2);
starts.Add(breakStart3);
ends.Add(breakEnd1);
ends.Add(breakEnd2);
ends.Add(breakEnd3);
for (int i = 0; i < starts.Count; i++)
{
var breaks = new List<Break>()
{
//for (int j= 0; j<starts.Count; j++)
//{
new Break()
{
MealStart = starts[i],
MealEnd = ends[i]
}
// }
};
var ordered = breaks.OrderBy(s => s.MealStart);
foreach (var ord in ordered)
{
System.Console.WriteLine(ord.MealStart);
System.Console.WriteLine(ord.MealEnd);
}
}
I am expecting a result like below
breakStart1 = 15/02/12 11.00AM
breakEnd1= 15/02/12 12.00PM
breakStart2 = 15/02/12 12.00PM
breakEnd2= 15/02/12 01.00PM
breakStart3 = 15/02/12 12.30PM
breakEnd3= 15/02/12 01.30PM
but it's not because of the for loop.
You are creating breaks after ever loop, you need to do this outside of the loop like this:
IList<DateTime> starts = new List<DateTime>();
IList<DateTime> ends = new List<DateTime>();
DateTime breakStart1 = new DateTime(2012, 02, 15, 12, 30, 00); // 15/02/12 12.30PM
DateTime breakEnd1 = new DateTime(2012, 02, 15, 13, 30, 00); // 15/02/12 01.30PM
DateTime breakStart2 = new DateTime(2012, 02, 15, 11, 00, 00); // 15/02/12 11.00AM
DateTime breakEnd2 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakStart3 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakEnd3 = new DateTime(2012, 02, 15, 01, 00, 00); // 15/02/12 01.00PM
starts.Add(breakStart1);
starts.Add(breakStart2);
starts.Add(breakStart3);
ends.Add(breakEnd1);
ends.Add(breakEnd2);
ends.Add(breakEnd3);
List<Break> breaks = new List<Break>();
for (int i = 0; i < starts.Count; i++)
{
breaks.Add(new Break()
{
MealStart = starts[i],
MealEnd = ends[i]
});
}
var ordered = breaks.OrderBy(s => s.MealStart);
foreach (var ord in ordered)
{
System.Console.WriteLine(ord.MealStart);
System.Console.WriteLine(ord.MealEnd);
}
Since #Corylulu beat me to the punch on the basic issue, here's a different method that is slightly shorter:
IEnumerable<Break> breaks =
starts.Zip(ends, (s, e) => new Break { MealStart = s, MealEnd = e })
.OrderBy(b => b.MealStart);
foreach (Break brk in breaks)
Console.WriteLine("Start: {0}\tEnd: {1}", brk.BreakStart, brk.BreakEnd);
The IEnumerable.Zip method takes a pair of IEnumerables and a transform function and produces an output IEnumerable containing the results of calling the transform function with members of each input IEnumerable. You could convert it to a List<Break> with a ToList() at the end of course.
Related
I writted code for automatical changer of shifts. Night shift, morning shift, etc. Everything works fine. Current problem with this is when is new month. 5 Month has 31 days. This month have 30 days.
My current code is this:
DateTime lastTime = _lastDateOfLoading;
DateTime tempTime = Convert.ToDateTime(hourOfLoading);
DateTime targetTime = new DateTime(DateOfLoading.Year, DateOfLoading.Month, DateOfLoading.Day, tempTime.Hour, tempTime.Minute, tempTime.Second);
DateTime currentTime = DateTime.Now;
bool tt1 = false;
bool tt2 = false;
bool lt1 = false;
bool lt2 = false;
DateTime lt1Min = new DateTime(currentTime.Year, currentTime.Month, lastTime.Day, 22, 00, 00);
DateTime lt1Max = new DateTime(currentTime.Year, currentTime.Month, lastTime.Day, 23, 59, 59, 999);
DateTime lt2Min = new DateTime(currentTime.Year, currentTime.Month, lastTime.Day, 00, 00, 00);
DateTime lt2Max = new DateTime(currentTime.Year, currentTime.Month, lastTime.Day, 06, 00, 00);
DateTime tt1Min = new DateTime(currentTime.Year, currentTime.Month, targetTime.Day, 22, 00, 00);
DateTime tt1Max = new DateTime(currentTime.Year, currentTime.Month, targetTime.Day, 23, 59, 59, 999);
DateTime tt2Min = new DateTime(currentTime.Year, currentTime.Month, targetTime.Day, 00, 00, 00);
DateTime tt2Max = new DateTime(currentTime.Year, currentTime.Month, targetTime.Day, 06, 00, 00);
if ((lastTime >= lt1Min
&& (lastTime < lt1Max)))
{
lt1 = true;
}
etc ..
It end on lt1Min = new DateTime ...
I think it happen because is june. And lastTime is 22.5.
Any advice how to solve this thing? Nothing helped on current threads here on stackoverlow.
Thank you.
I am trying to get the time closer to 24:00:00 between two values, before midnight and after midnight.
EDIT: This is just an an example of what I am trying to do. In this case I should get both items.
var dt1 = new DateTime(2014, 11, 11, 23, 50, 00);
var dt2 = new DateTime(2014, 12, 11, 00, 50, 00);
var l = new List<DateTime>();
for (int i = 0; i < l.Count - 1; i++)
{
TimeSpan ts1 = new TimeSpan(l[i].Hour, l[i].Minute, l[i].Second);
TimeSpan ts2 = new TimeSpan(l[i + 1].Hour, l[i + 1].Minute, l[i + 1].Second);
if (ts1.TotalHours <= 23 && ts2.TotalHours >= 00)
{
Console.WriteLine("00:00:00 - {0} {1} \n", ts1, ts2);
}
}
Thank you for any help and advise.
Your question is quite confusing and not totally clear what it is you're trying to achieve, but I've made some assumptions, and come up with what I think maybe what you're after:
var l = new List<DateTime> {
new DateTime(2014, 11, 11, 22, 0, 0),
new DateTime(2014, 11, 11, 23, 45, 0),
new DateTime(2014, 11, 11, 23, 55, 0),
new DateTime(2014, 11, 11, 23, 59, 59),
new DateTime(2014, 11, 12, 0, 0, 0),
new DateTime(2014, 11, 12, 0, 4, 0),
new DateTime(2014, 11, 12, 0, 15, 0),
new DateTime(2014, 11, 12, 1, 0, 0),
new DateTime(2014, 11, 12, 10, 0, 0),
};
for (int i = 0; i < l.Count - 1; i++) {
if (l[i].TimeOfDay.TotalMinutes < 5 || l[i].TimeOfDay.TotalMinutes >= 23*60 + 55)
Console.WriteLine("{0} is close to midnight", l[i]);
else
Console.WriteLine("{0} is NOT close to midnight", l[i]);
}
I've loaded the list of dates/times with some test data, and the code simply prints out whether each date/time is within 5 minutes either side of midnight.
Another attempt at answering you're ambiguous question is as follows:
var l = new List<DateTime> {
new DateTime(2014, 11, 11, 15, 0, 0), // 15:00:00
new DateTime(2014, 11, 11, 16, 0, 0), // 16:00:00
new DateTime(2014, 11, 11, 17, 0, 0), // 17:00:00
new DateTime(2014, 11, 11, 17, 20, 0), // 17:20:00
new DateTime(2014, 11, 11, 18, 15, 0), // 18:15:00
new DateTime(2014, 11, 11, 19, 0, 0), // 19:00:00
new DateTime(2014, 11, 11, 22, 0, 0), // 22:00:00
new DateTime(2014, 11, 11, 23, 45, 0), // 23:45:00
new DateTime(2014, 11, 11, 23, 50, 00), // 23:50:00
new DateTime(2014, 12, 11, 00, 50, 00), // 00:50:00
new DateTime(2014, 11, 12, 1, 0, 0), // 01:00:00
new DateTime(2014, 11, 12, 10, 0, 0), // 10:00:00
};
var time = new TimeSpan(18, 0, 0); // <- Set the target time here
var offsetBefore = new TimeSpan(1, 0, 0, 0).TotalMilliseconds - time.TotalMilliseconds;
var offsetAfter = time.TotalMilliseconds * -1;
var closestBefore =
l.Aggregate(
(current, next) =>
next.AddMilliseconds(offsetBefore).TimeOfDay.TotalMilliseconds > current.AddMilliseconds(offsetBefore).TimeOfDay.TotalMilliseconds
? next
: current);
var closestAfter =
l.Aggregate(
(current, next) =>
next.AddMilliseconds(offsetAfter).TimeOfDay.TotalMilliseconds < current.AddMilliseconds(offsetAfter).TimeOfDay.TotalMilliseconds
? next
: current);
Console.WriteLine("{0} is the closest date/time before {1}.", closestBefore, time);
Console.WriteLine("{0} is the closest date/time after {1}.", closestAfter, time);
Console.WriteLine("00:00:00 - {0} {1} \n", closestBefore, closestAfter);
// OUTPUTS:
// 11/11/2014 17:20:00 is the closest date/time before 18:00:00.
// 11/11/2014 18:15:00 is the closest date/time after 18:00:00.
// 00:00:00 - 11/11/2014 17:20:00 11/11/2014 18:15:00
This will return the closest date/time in the list to midnight that is before midnight, and also separately the closest date/time in the list to midnight that is after midnight.
Hope this helps!
Try this:
var dt1 = new DateTime(2014, 11, 11, 23, 50, 00);
var dt2 = new DateTime(2014, 12, 11, 00, 50, 00);
var dt1temp = new DateTime(dt1.Year, dt1.Month, dt1.Day, 00, 00, 00);
var dt2temp = new DateTime(dt2.Year, dt2.Month, dt2.Day, 00, 00, 00);
TimeSpan time1 = new TimeSpan();
TimeSpan time2 = new TimeSpan();
TimeSpan time24 = new TimeSpan(24, 0, 0);
time1 = dt1 - dt1temp;
time2 = dt2 - dt2temp;
if (time1.Hours >= 12) time1 = time24 - time1;
if (time2.Hours >= 12) time2 = time24 - time2;
string result = "";
if (time1 < time2) result = "Time1 nearer to 00:00";
else result = "Time2 nearer to 00:00";
I'm trying to seed a database with two lists. The first list is just a bunch of items. The second list is a bunch of junk that references the first list. I'm trying to reference items from first list in the second list of junk, via LINQ, but I'm fairly certain I'm not doing it right:
For example, List 1:
var items = new List<Item>()
{
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Cheese" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Lettuce" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Ground Beef" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 03, 12, 30, 30), Text = "Ketchup" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 03, 12, 30, 30), Text = "Mustard" },
};
var junk= new List<Junk>()
{
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 05).ToShortDateString()},
new Junk { JunkId = 2, DateTime = new DateTime(2014, 09, 03, 11, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 03).ToShortDateString()}
};
This seems like it should be the answer to me, because I'm only interested in the date and not the time, but it doesn't seed like this. I get the error:
LINQ to Entities does not recognize the method 'System.String
ToShortDateString()' method, and this method cannot be translated into
a store expression.
Any thoughts on how to build a better solution?
UPDATE
Looks like I didn't transcribe my code accurately to the site, and ended up finding my problem.
In my original code, I had:
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = context.Items.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05) }
When I should have had
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05) }
I'd been flirting with .ToShortDateString() unnecessarily
Change filter to:
.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05))
You can use TruncateTime function of EntityFunctions Class.
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => EntityFunctions.TruncateTime(d.DateTime) == EntityFunctions.TruncateTime(new DateTime(2014, 09, 05))}
Note: If you using EntityFramework 6 then it should be System.Data.Entity.DbFunctions.TruncateTime(...) method from EntityFramework.dll.
Your subquery (the Items = part of the Junk variable) isn't a list but an enumerable, so it doesn't get materialized untill it's enumerated, and it's not enumerated untill you use it, down the road, in your linq to entities query.
If you change it as such :
var junk= new List<Junk>()
{
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 05).ToShortDateString()).ToList()}, // this one will work as it gets materialized right now, not later, so by the time you pass it to linq to entities later it will already be a simple list of diferences, it won't try to compute "toshortdatestring" later, that will already be done
new Junk { JunkId = 2, DateTime = new DateTime(2014, 09, 03, 11, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 03).ToShortDateString()}
};
Getting InvalidOperationException or sometimes TargetInvocationException, When Control reaches at this function the Exception thrown.
private void setreminders()
{
DateTime Date1 = new DateTime(2014, 02, 10, 06, 00, 00);
DateTime Date2 = new DateTime(2014, 02, 10, 07, 30, 00);
Reminder _Reminder1 = new Reminder("TodoReminder")
{
BeginTime = Date1,
Title = "Diet Reminder",
Content = "Its time to wake up, Have a Glass of Water and Start Excercising like YOGA & PRANAYAMA",
};
_Reminder1.RecurrenceType = RecurrenceInterval.Daily;
ScheduledActionService.Add(_Reminder1);
Reminder _Reminder2 = new Reminder("TodoReminder")
{
BeginTime = Date2,
Title = "Diet Reminder",
Content = "Drink a Glass of Water",
};
_Reminder2.RecurrenceType = RecurrenceInterval.Daily;
ScheduledActionService.Add(_Reminder2);
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Earlier I had posted the question Sorting Date and Time.
It was answered by mipe34, but I am stuck trying to use the solution inside my code.
Here's that I did so far. I created a class as follows:
public class Meals
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
In my main class I have the following method that has date pair values:
IList<DateTime> starts = new List<DateTime>();
IList<DateTime> ends = new List<DateTime>();
DateTime breakStart1 = new DateTime(2012, 02, 15, 12, 30, 00); // 15/02/12 12.30PM
DateTime breakEnd1 = new DateTime(2012, 02, 15, 13, 30, 00); // 15/02/12 01.30PM
DateTime breakStart2 = new DateTime(2012, 02, 15, 11, 00, 00); // 15/02/12 11.00AM
DateTime breakEnd2 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakStart3 = new DateTime(2012, 02, 15, 12, 00, 00); // 15/02/12 12.00PM
DateTime breakEnd3 = new DateTime(2012, 02, 15, 01, 00, 00); // 15/02/12 01.00PM
starts.Add(breakStart1);
starts.Add(breakStart2);
starts.Add(breakStart3);
ends.Add(breakEnd1);
ends.Add(breakEnd2);
ends.Add(breakEnd3);
for (int i = 0; i < starts.Count; i++)
{
var breaks = new List<Break>()
{
//for (int j= 0; j<starts.Count; j++)
//{
new Break()
{
MealStart = starts[i],
MealEnd = ends[i]
}
// }
};
var ordered = breaks.OrderBy(s => s.MealStart);
foreach (var ord in ordered)
{
System.Console.WriteLine(ord.MealStart);
System.Console.WriteLine(ord.MealEnd);
}
}
How can I pass all my date pairs and use his solution? it doesn't bring back the expected value.
Start by creating objects and adding them to a list. You can use the collection initializer in this case.
var mealList = new List<Meals>
{
new Meals { Start = dtmealStart1, End = dtmealStart1 },
/* Repeat for the rest of them possibly incorporating some kind of loop to generate this list */
};
//and then get your sorted list
var sortedMealList = mealList.OrderBy(m => m.Start);