HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Writing the condition x <= y AND x > 0

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andwritingconditionthe

Problem

My current condition is written as follows:

.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0)  0)


which basically says where the rounded value is less than or equal to 30 and the rounded value is greater than 0.

Is there a neater way to write this than having

Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0)


twice in the same statement?

The full expression is:

List finalList = initialList.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0)  0).ToList();

Solution

If you need to store a result of a method you should just create a method for it.

private bool IsInRange(DateTime dateTime, decimal min, decimal max)
{
    decimal totalMinutes = Math.Round((dateTime - DateTime.Now).TotalMinutes, 0);
    return totalMinutes > min && totalMinutes <= max;
}


now your expression looks like so

.Where(m => IsInRange(m.DateAndTime, 0, 30));


but the values 0 and 30 are still magic numbers which should be extracted to meaningful constants.

The choosen method name is not the best like @Falco has correctly pointed out in his comment


UhhOhhh Horribly wrong named Function.... AreMinutesInRangeFromNow or something like this would be better - with your Method-Name I would expect no Magic happening with DateTime.Now - or pass the already substracted value, but don't hide this!

so you should change it to a better name. I don't like the name @Falco suggested either but couldn't come up with a different one. So it is up to you to choose one.

Code Snippets

private bool IsInRange(DateTime dateTime, decimal min, decimal max)
{
    decimal totalMinutes = Math.Round((dateTime - DateTime.Now).TotalMinutes, 0);
    return totalMinutes > min && totalMinutes <= max;
}
.Where(m => IsInRange(m.DateAndTime, 0, 30));

Context

StackExchange Code Review Q#97672, answer score: 22

Revisions (0)

No revisions yet.