Can you assign a value only if its greater / less than the current value?

StackOverflow https://stackoverflow.com/questions/23419396

  •  13-07-2023
  •  | 
  •  

Вопрос

I'm wondering if there's an operator to simplify this? Similar to the += operator.

if (x > val) x = val;
x "new operator" val;


//date times
DateTime d1 = dsi_curr.cycleSteps.StepsUpTimestamp[0] ;
DateTime d2 = dsi_curr.cycleSteps.StepsUpTimestamp[dsi_curr.cycleSteps.StepsUpTimestamp.Length-1];

if (d1 < curbt.details.StartDate) {
    curbt.details.StartDate = d1;
}
if (d2 > curbt.details.EndDate) {
    curbt.details.EndDate = d2;
}
Это было полезно?

Решение

There is no builtin operator for this, but you can add your own method to simplify this:

static void MakeLesserOf(ref DateTime self, DateTime other) {
    self = self > other ? other : self;
}
static void MakeGreaterOf(ref DateTime self, DateTime other) {
    self = self < other ? other : self;
}

Now you can rewrite your code as follows:

MakeLesserOf(curbt.details.StartDate, d1);
MakeGreaterOf(curbt.details.EndDate, d2);

Другие советы

For simple types you can use Math.Min() and Math.Max(), but not with DateTime.

It will still do the assignment, but it will re-assign the lower/higher value.

If you're looking for how to simplify your conditional expressions, you can use the conditional operator (?:) as mentioned by JleruOHeP in the comments.

curbt.details.StartDate = (d1 < curbt.details.StartDate) ? d1 : curbt.details.StartDate;
curbt.details.EndDate = (d2 > curbt.details.EndDate) ? d2 : curbt.details.EndDate;

Though in this particular case I would just write the if without the linebreaks:

if (d1 < curbt.details.StartDate) curbt.details.StartDate = d1;
if (d2 > curbt.details.EndDate) curbt.details.EndDate = d2;

Let me know if I've misunderstood your question.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top