我正在使用锯齿状数组,并且遇到了一些问题(或者至少我认为我有问题)。这些数组的大小取决于数据库中返回的行数,因此变化很大。我唯一的解决方案是将数组的维度设置得非常大,但这似乎……并不是最好的方法。
int[][] hulkSmash = new int[10][];
hulkSmash[0] = new int[2] {1,2};
如何在不设置维度的情况下使用锯齿状数组,或者这只是 C# 编程的一个事实?
I'm using jagged arrays and have a bit of a problem (or at least I think I do). The size of these arrays are determined by how many rows are returned in a database, so it is very variable. The only solution I have is to set the dimensions of the array to be very huge, but this seems ... just not the best way to do things.
int[][] hulkSmash = new int[10][];
hulkSmash[0] = new int[2] {1,2};
How can I work with jagged arrays without setting the dimensions, or is this just a fact of life with C# programming??
发布评论
评论(4)
您有 2 个选择:
You've got 2 choices:
使用
List
和集合的其他示例是继续的最佳方法。我有时发现语法有点笨拙。幸运的是,有一些选项可以解决这个问题。
我有时使用的第一个选项是创建别名:
这可以防止您一直执行嵌套
<<>>
。无论您在何处输入List
,您都可以输入>
HulkSmashCollection
(或更短的内容)。第二个选项是将列表列表包装在名为 MyHulkSmashes 的类中。在这里,您只需提供所需的函数/属性,例如
Count
或Find()
等。这两个概念都用于减少屏幕上的代码量,并减少感知的复杂性。
The other examples using
List<T>
and collections are the best way to proceed. I sometimes find thesyntax a tad unwieldy. Luckily, there are some options to manage this.
The first option I sometimes use is to make an alias:
This prevents you from having to do nested
<<<Types>>>
all the time. Everywhere you'd typeList<List<int>>
you can instead typeHulkSmashCollection
(or something shorter still) instead.The second option is to wrap the List of Lists within a class called, say, MyHulkSmashes. Here, you only provide the functions/properties you need, like
Count
orFind()
etc.Both these concepts are used to reduce the amount of code on screen, and reduce perceived complexity.
或者
or
整数集合(例如 List)将为您提供所需的灵活性,并且不会像分配比您需要的大得多的数组那样浪费空间。
A collection of ints (such as List) will give you the flexibility that you want and not waste space as would allocating an array that is much larger than you will ever need.