0

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,
    });
}
jps
  • 20,041
  • 15
  • 75
  • 79
SideSky
  • 313
  • 3
  • 15
  • 1
    If the collection is a common List then you can't avoid to check if the item exists and add a new item of not. What you can do to make your code reusable and more readble is to move the coffee to a e.g. UpdateOrCreateBottomAxis(double) – BionicCode Sep 28 '21 at 11:16

1 Answers1

1

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,
    });
}
mm8
  • 163,881
  • 10
  • 57
  • 88