Home > Software engineering >  Create object with special property if it does not exist yet
Create object with special property if it does not exist yet

Time:09-30

I have an OxyPlot with an X and a Y axis where I want to change the maximum values several times. To change them, I have to create the axes first.
Is there a nicer way to edit for example the X-axis (AxisPosition.Bottom) if it exists and if not to create a new one?

This is my code right now:

if (opGraph.Axes.Any(s => s.Position == AxisPosition.Bottom))
{
    OxyPlot.Wpf.Axis xAxis = opGraph.Axes.FirstOrDefault(s => s.Position == AxisPosition.Bottom);
    xAxis.AbsoluteMaximum = absoluteMaximum;
}
else
{
    opGraph.Axes.Add(new OxyPlot.Wpf.LinearAxis
    {
        Position = AxisPosition.Bottom,
        AbsoluteMaximum = absoluteMaximum,
    });
}

CodePudding user response:

It's not necassary to first call Any and then also FirstOrDefault. This results in double iterations.

The latter alone does the job:

OxyPlot.Wpf.Axis xAxis = opGraph.Axes.FirstOrDefault(s => s.Position == AxisPosition.Bottom);
if (xAxis != null)
{
    xAxis.AbsoluteMaximum = absoluteMaximum;
}
else
{
    opGraph.Axes.Add(new OxyPlot.Wpf.LinearAxis
    {
        Position = AxisPosition.Bottom,
        AbsoluteMaximum = absoluteMaximum,
    });
}
  • Related