【发布时间】:2011-06-25 02:38:13
【问题描述】:
我想要一个包含 2 个 Int32 值的数组,比如:
Int32 x
Int32 y
我想列出这些数组。
- 如何声明和初始化这个数组和列表?
- 填充列表后如何访问列表成员?
【问题讨论】:
标签: c# arrays list data-structures
我想要一个包含 2 个 Int32 值的数组,比如:
Int32 x
Int32 y
我想列出这些数组。
【问题讨论】:
标签: c# arrays list data-structures
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 值的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 更合适。
没有足够的信息来说明您想要什么。但这里有一个初始化 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;
【讨论】:
嗯,有两种类型的数组。多维数组和锯齿状数组。您可以使用任何一种(更多关于它们的区别,请访问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}};
希望这有助于澄清一些事情。如果您指的是实际列表,请查看其他答案。
【讨论】:
使用仅包含两个 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<List<int, int>> 或 List<int[]>)上使用 List<Tuple<int, int>> 的好处是您明确强制列表项仅是两个整数。
【讨论】: