【问题标题】:How to make a list of an array of ints?如何制作一个整数数组的列表?
【发布时间】:2011-06-25 02:38:13
【问题描述】:

我想要一个包含 2 个 Int32 值的数组,比如:

 Int32 x
 Int32 y

我想列出这些数组。

  • 如何声明和初始化这个数组和列表?
  • 填充列表后如何访问列表成员?

【问题讨论】:

    标签: c# arrays list data-structures


    【解决方案1】:
    List<int[]> l = new List<int[]>();
    
    l.Add(new int[] { 1, 2 });
    l.Add(new int[] { 3, 4 });
    
    int a = l[1][0];   // a == 3
    

    【讨论】:

    • 如果你真的使用 x 和 y 作为两个整数数组。您可以使用现有的类或创建自己的类。然后你可以只使用 List 或 List
    【解决方案2】:

    听起来您正在尝试将数组转换为数据结构,而不是通过按顺序存储值。不要这样做。了解如何使用更高级的数据结构来发挥自己的优势。

    您提到了具有xy 值的Point 类型。来一堂课怎么样?

    class Point
    {
        public readonly int X;
        public readonly int Y;
        public Point( int x, int y )
        {
            X = x;
            Y = y;
        }
    }
    

    现在您可以创建新类型的实例并将它们添加到列表中,从而简化整个过程并确保您不会滑倒并在您的数组中添加 x,其中 y应该是。

    List<Point> ls = new List<Point>();
    ls.Add( new Point( 0, 0 ) );
    ls.Add( new Point( 10, 10 ) );
    ls.Add( new Point( 100, 100 ) );
    

    无论如何,了解如何在 C# 中创建自己的数据结构是个好主意。学习如何以易于使用的方式适当地存储数据有很多好处。

    【讨论】:

    • 对于某个点来说,struct 可能比 class 更合适。
    • @icktoofay:我在等别人这么说=)。我真的不想涉及值类型与引用类型。 OP显然是初学者。我认为最好尽可能简单地展示一个示例,因为他需要采取下一步措施并在更深层次上自己了解这些东西。
    【解决方案3】:

    没有足够的信息来说明您想要什么。但这里有一个初始化 Int32 数组的通用列表的基本示例。我希望这会有所帮助

            Int32 x = 1; 
            Int32 y = 2;
    
            // example of declaring a list of int32 arrays
            var list = new List<Int32[]> {
                new Int32[] {x, y}
            };
    
            // accessing x
            list[0][0] = 1;
    
            // accessing y
            list[0][1] = 1;
    

    【讨论】:

      【解决方案4】:

      嗯,有两种类型的数组。多维数组和锯齿状数组。您可以使用任何一种(更多关于它们的区别,请访问http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx)。

      一个交错数组的例子:

      Int32[][] = new Int32[] { new Int32[] {1,2}, new Int32[] {3,4}};
      

      一个多维数组的例子:

      Int32[,] = new Int32[,] {{1,2},{3,4}};
      

      希望这有助于澄清一些事情。如果您指的是实际列表,请查看其他答案。

      【讨论】:

        【解决方案5】:

        使用仅包含两个 int32 的元组列表:

        List<Tuple<int, int>> myList = new List<Tuple<int, int>>();
        
        var item = new Tuple<int, int>(25, 3);
        
        myList[0] = new Tuple<int, int>(20, 9);//acess to list items by index index
        
        myList.Add(item);//insert item to collection
        
        myList.IndexOf(item);//get the index of item
        
        myList.Remove(item);//remove item from collection
        

        在第二个列表(如 List&lt;List&lt;int, int&gt;&gt;List&lt;int[]&gt;)上使用 List&lt;Tuple&lt;int, int&gt;&gt; 的好处是您明确强制列表项仅是两个整数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-10
          • 2016-05-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多