【问题标题】:Create object with special property if it does not exist yet如果对象尚不存在,则创建具有特殊属性的对象
【发布时间】:2021-09-28 09:49:31
【问题描述】:

我有一个带有 X 轴和 Y 轴的 OxyPlot,我想在其中多次更改最大值。要更改它们,我必须先创建轴。
有没有更好的方法来编辑例如 X 轴 (AxisPosition.Bottom) 如果它存在并且如果不创建一个新的?

这是我现在的代码:

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,
    });
}

【问题讨论】:

  • 如果该集合是一个普通的List,那么你不能避免检查该项目是否存在并添加一个不存在的新项目。为了使代码可重用和更具可读性,您可以做的是将咖啡移至例如UpdateOrCreateBottomAxis(double)

标签: c# wpf object oxyplot


【解决方案1】:

不必先调用Any,然后再调用FirstOrDefault。这会导致两次迭代。

后者独自完成这项工作:

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,
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2016-05-03
    • 2016-07-13
    相关资源
    最近更新 更多