【问题标题】:Do the items in an array or list maintain their order?数组或列表中的项目是否保持其顺序?
【发布时间】:2010-10-05 13:29:19
【问题描述】:

我正在用 VS2008 编写 VB.NET。

我有一个逗号分隔的数字字符串,即 16,7,99,1456,1,3

我在 VB 中这样做:

Dim MyArr() As String = MyString.Split(",")

MyArr 会按照它们在字符串中的顺序保留项目吗?

如果我这样做:

For Each S as String in MyString.Split(",")
    'Do something with S
    'Will my items be in the same order they were
    'in the string?
Next

我对其进行了测试,它似乎保持了排序顺序,但它会~总是~保持顺序吗?

如果它不保持顺序,那么拆分字符串并保持顺序的好方法是什么?

我之所以问,是因为 MSDN 数组文档说:“数组不能保证被排序。”所以我有点不确定。

【问题讨论】:

    标签: vb.net arrays string sorting


    【解决方案1】:

    是的,在您的示例中,项目将保持原始顺序。

    MSDN 文档指出 Array 不一定因为它是 Array 而排序,但是一旦项目在 Array 中,它们就不会重新排列。 Split() 操作将根据给定的标记将其分解,并保留顺序。

    【讨论】:

    • 是的。我认为“保存”是要记住的关键问题。
    • 这就是我想要的澄清。谢谢。
    【解决方案2】:

    是的,这些操作将保持秩序。

    【讨论】:

      【解决方案3】:

      是的,String.Split 遍历字符串,一切都将保持有序。来自 .NET 反射器:

      private string[] InternalSplitKeepEmptyEntries(int[] sepList, int[] lengthList, int numReplaces, int count)
      {
          int startIndex = 0;
          int index = 0;
          count--;
          int num3 = (numReplaces < count) ? numReplaces : count;
          string[] strArray = new string[num3 + 1];
          for (int i = 0; (i < num3) && (startIndex < this.Length); i++)
          {
              strArray[index++] = this.Substring(startIndex, sepList[i] - startIndex);
              startIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
          }
          if ((startIndex < this.Length) && (num3 >= 0))
          {
              strArray[index] = this.Substring(startIndex);
              return strArray;
          }
          if (index == num3)
          {
              strArray[index] = Empty;
          }
          return strArray;
      }
      

      【讨论】:

      • 我有点误读了这个问题。 Serguei 有一个更清晰更准确的答案。
      【解决方案4】:

      .NET 中的字符串是immutable objects。长话短说,字符串 S 和 Split(",") 返回的字符串存在于不同的内存中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 2010-12-05
        相关资源
        最近更新 更多