Search code examples
c#linqgrasshopper

Using a LINQ variable in another method?


In the code below, I am trying to assign the array Filepaths to the variable m_settings but Filepaths is not recognized outside the LINQ method. How can I store the content of FilePaths in a variable that i can use in the SolveInstance method?

public void ShowSettingsGui()
{
    var dialog = new OpenFileDialog()
    {
        Multiselect = true,
        Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*"
    };
    if (dialog.ShowDialog() != DialogResult.OK) return;
    var paths = dialog.FileNames;
    var FilePaths = paths.ToDictionary(filePath => filePath, File.ReadAllText);
}

private string[] m_settings = Filepaths;  

protected override void SolveInstance(IGH_DataAccess DA)
{
    if (m_settings == null)
    {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You must declare some valid settings");
        return;
    }

    DA.SetData(0, m_settings);
}

Solution

  • I could be reading into it too much but I don't think you need FilePaths, you can just set m_settings directly...

    private Dictionary<string, string> m_settings;  
    
    public void ShowSettingsGui()
    {
        var dialog = new OpenFileDialog()
        {
            Multiselect = true,
            Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*"
        };
        if (dialog.ShowDialog() != DialogResult.OK) return;
        var paths = dialog.FileNames;
        m_settings = paths.ToDictionary(filePath => filePath, File.ReadAllText);
    }
    
    protected override void SolveInstance(IGH_DataAccess DA)
    {
        if (m_settings == null)
        {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You must declare some valid settings");
            return;
        }
    
        DA.SetData(0, m_settings);
    }
    

    You also need to ensure SolveInstance is called after ShowSettingsGui, otherwise m_settings will always be null