【问题标题】:Why I add a new item to a List<string> it's adding it to the bottom of the list?为什么我将一个新项目添加到 List<string> 它将它添加到列表的底部?
【发布时间】:2014-06-22 07:52:10
【问题描述】:

第一次将它添加到顶部时,我看到了列表:

1 2 3 4 5

但是在下一次第一次之后,一个新项目被添加到底部,我希望它在顶部。 而不是 6 号,新项目应该是 1 号和 6 号。

这就是我每次添加 3 个项目时构建列表的方式:

newText.Add(t[i]);
newText.Add(dateTime[i]);
newText.Add(string.Empty);

然后我制作一个过滤器来匹配特定的字符串(单词):

FilterWords.CheckIfWordsExistInList(newText);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using mshtml;
using System.IO;


namespace ScrollLabelTest
{
    class FilterWords
    {
        public static void CheckIfWordsExistInList(List<string> newText)
        {
            // start at the bottom in the first line "that matters" and go down by 3
            for (int x = newText.Count - 3; x >= 0; x -= 3)
            {
                // check if the line contains any of the words specified
                if (!WordsList.words.Any(w => newText[x].Contains(w)) || newText[x] == "")
                {
                    // remove the checked line as well as the next two if not
                    newText.RemoveRange(x, 3);
                }
            }

            ExtractLinks.CheckIfResponseContainWords();
        }
    }
}

然后在我有一个字符串,我将列表 newText 中的项目分配给它:

private void CombindedStringFix()
{
    combindedString = string.Join(Environment.NewLine, newText);
    string[] ss = combindedString.Split(new string[] { "\n", "\r\n" },
                      StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < ss.Length; i++)
        ss[i] = ss[i].Trim();

    combindedString = String.Join("\n", ss);

    string[] lines = combindedString.Split(new string[] { "\n", "\r\n" },
             StringSplitOptions.RemoveEmptyEntries);

    combindedString = String.Empty;

    for (int i = 0; i < lines.Length; i++)
    {
         if (i % 2 == 0)
            combindedString += Environment.NewLine;

         combindedString += lines[i].Trim() + Environment.NewLine;
    }

    scroller1.TextToScroll = combindedString;
    m_textToScroll.Text = combindedString;
    m_textToScroll.Text = m_textToScroll.Text.TrimStart();
}

但每次添加新文本时,我都会在 scroller1 和底部的 m_textToScroll 中看到它。

【问题讨论】:

  • 会使用Stack&lt;string&gt; 帮助吗?还是您实际上想要添加一组特定的、有限的值并且应该使用强类型模型?

标签: c# .net winforms


【解决方案1】:

如果您只是想在列表中的特定位置添加一个项目,那么只需使用 insert(index,object) 而不是添加。因此,在您的情况下,您会将其添加到索引 0。

然后,这会将所有其他项目向下移动。

默认情况下,添加只是为您将其粘贴在列表的末尾。

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    相关资源
    最近更新 更多