简体   繁体   English

如果尚不存在,则创建具有特殊属性的 object

[英]Create object with special property if it does not exist yet

I have an OxyPlot with an X and a Y axis where I want to change the maximum values several times.我有一个带有 X 轴和 Y 轴的OxyPlot ,我想在其中多次更改最大值。 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?是否有更好的方法来编辑例如 X 轴 (AxisPosition.Bottom)(如果存在)以及是否创建新轴?

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

It's not necassary to first call Any and then also FirstOrDefault .不必先调用Any然后再调用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,
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么方法可以返回一个尚不存在的对象,但稍后会从C#方法返回? - Any way to return an object which does not exist yet but will later from a C# method? 引用未实例化/尚不存在的类 - Referencing a class that is not instantiated / does not yet exist 变量在上下文中不存在,但它是明确定义的 - Variable does not exist in context, yet it is clearly defined 更新属性或创建新元素(如果它不存在)Lambda c# - Update property or create new element if it does not exist Lambda c# 如果 object 中的属性不存在,则 c# 添加 null - c# add null if property in an object does not exist 命名空间中不存在类型或命名空间名称 - 但命名空间确实存在 - Type or namespace name does not exist in the namespace - yet the namespaces do exist 如果文件夹不存在,则创建它 - If a folder does not exist, create it 表不存在就创建? - Create a table if it does not exist? 当实体的表尚不存在时,实体框架的行为是什么? - What is the behavior of entity framework when a table does not exist yet for an entity? DataGridViewCellCollection 的属性 Item 不存在 - The property Item of DataGridViewCellCollection does not exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM