Note that there are some explanatory texts on larger screens.

plurals
  1. POLinq lambda expression - Find the closest day of week to current date (now)
    primarykey
    data
    text
    <p>I have for example Monday, Thursday and Sunday as draw dates. What would be the way to find the closest dayOfWeek to Datetime.Now with Linq Lambda? I accomplished this with normal function, but I would like to know how to do it with Linq Lambda?</p> <p>Example of my approach:</p> <pre><code> public static DateTime GetSoonestDrawDate(this DateTime from, IEnumerable&lt;LotteryDrawDate&gt; drawDates) { int hour = 0; int minute = 0; bool todayDrawOnly = true; int difference = 7; int tempDifference = 0; int todayDay = (int)from.DayOfWeek; int drawCutOffDay = 0; if (todayDay == 0) { todayDay = 7; } var tempCutOffTime = new TimeSpan(23, 59, 59); foreach (var drawDate in drawDates) { // DayId is DayOfWeek drawCutOffDay = drawDate.DayId; if (drawCutOffDay &lt; todayDay) { drawCutOffDay += 7; } tempDifference = drawCutOffDay - todayDay; var cutOffTime = new TimeSpan(); cutOffTime = TimeSpan.Parse(drawDate.CutOffTime); if ((difference &gt; tempDifference) || difference == 0) { // draw date is not today if (tempDifference != 0) { difference = tempDifference; hour = cutOffTime.Hours; minute = cutOffTime.Minutes; todayDrawOnly = false; } // same day, cutOffTime still available if ((tempDifference == 0 &amp;&amp; cutOffTime &gt; from.TimeOfDay)) { // we use tempCutOffTime to compare newest cutOffTime in case we have more cutOffTimes on the same day // in that case we have to select the soonest cutOffTime of the day if (cutOffTime &lt; tempCutOffTime) { difference = tempDifference; hour = cutOffTime.Hours; minute = cutOffTime.Minutes; todayDrawOnly = true; tempCutOffTime = cutOffTime; } } // same day selected only, but cutOffTime passed, so we add another week only in case there is only one draw date and draw date is on the same day else if (tempDifference == 0 &amp;&amp; cutOffTime &lt; from.TimeOfDay &amp;&amp; todayDrawOnly == true) { if (cutOffTime &lt; tempCutOffTime) { difference = 7; hour = cutOffTime.Hours; minute = cutOffTime.Minutes; todayDrawOnly = true; tempCutOffTime = cutOffTime; } } } } from = from.AddDays(difference); DateTime soonest = new DateTime(from.Year, from.Month, from.Day, hour, minute, 0); return soonest; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload