【问题标题】:Updating a string from a ΤextΒox从 ΤextΒox 更新字符串
【发布时间】:2013-08-12 04:01:16
【问题描述】:

在我正在制作的程序中,我在“设置”中创建了一个名为“Tickers”的字符串。范围为 Application,值为 "AAPL,PEP,GILD",不带引号。

我有一个名为 InputTickers 的 RichTextBox,用户应该在其中输入股票代码,例如 AAPL、SPLS 等。你明白了。当他们单击 InputTickers 下方的按钮时,我需要它来获取 Settings.Default["Tickers"]。接下来,我需要它检查他们输入的任何代码是否已经在代码列表中。如果没有,我需要添加它们。

添加后,我需要将其转回 Tickers 字符串以再次存储在设置中。

我还在学习编码,所以这是我最好的猜测,我在这方面已经走了多远。不过,我想不出如何正确完成这项工作。

private void ScanSubmit_Click(object sender, EventArgs e)
{
    // Declare and initialize variables
    List<string> tickerList = new List<string>();


    try
    {
        // Get the string from the Settings
        string tickersProperty = Settings.Default["Tickers"].ToString();

        // Split the string and load it into a list of strings
        tickerList.AddRange(tickersProperty.Split(','));

        // Loop through the list and do something to each ticker
        foreach (string ticker in tickerList)
        {
            if (ticker !== InputTickers.Text)
                 {
                     tickerList.Add(InputTickers.Text);
                 }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

【问题讨论】:

标签: c# string


【解决方案1】:

试试喜欢这个,

 foreach (string ticker in tickerList)
    {
        if (InputTickers.Text.Split(',').Contains(ticker))
             {
                 tickerList.Add(InputTickers.Text);
             }
    }

如果你的输入字符串有空格,

        if (InputTickers.Text.Replace(" ","").Split(',').Contains(ticker))
         {

         }

【讨论】:

    【解决方案2】:

    您可以将 LINQ 扩展方法用于集合。产生更简单的代码。首先,从设置中拆分字符串并将项目添加到集合中。其次,从文本框中拆分(您忘记了)字符串并添加这些项目。第三,使用扩展方法获取distinct列表。

    // Declare and initialize variables
    List<string> tickerList = new List<string>();
    
        // Get the string from the Settings
        string tickersProperty = Settings.Default["Tickers"].ToString();
    
        // Split the string and load it into a list of strings
        tickerList.AddRange(tickersProperty.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
        tickerList.AddRange(InputTickers.Text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
    
        Settings.Default["Tickers"] = String.Join(',', tickerList.Distinct().ToArray());
        Settings.Default["Tickers"].Save();
    

    【讨论】:

    • 嗯,这对我来说确实不错,所以我试了一下。它的某些部分不起作用,所以我一直在谷歌上搜索它。似乎无法弄清楚如何解决它。当前上下文中不存在 SplitOptions。让我们先尝试修复它。我错过了一个特殊的命名空间吗?如果是这样,我很难找到它。
    • 使用VisualStudio的Intellisense,你会找到正确的版本。我首先在没有 VisualStudio 的情况下写了我的答案。现在我检查了它并更正了上面的代码/方法。看看吧。
    猜你喜欢
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多