查找数组的最低空闲位置
我遇到了数组问题,我需要找到数组的最低空闲位置以将信息插入其中。我该怎么做呢?
例如,我有数组 string[] array = String[10]
,其中数组的某些位置已经填充,我需要在数组中选择一个位置,然后搜索返回到位置 0 哪些位置是空闲的,然后返回该值。
这可能很简单,但我完全被难住了,感谢您的帮助。
I'm having a problem with an array, I need to find the lowest free position of an array to insert information into it. How would I go about doing this?
For example I have array string[] array = String[10]
where by some of the positions of the array are already filled, I need to choose a spot in the array and then search going back to towards position 0 which spots are free and then return that value.
This is probably quite simple but I'm completely stumped, thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要循环遍历数组的所有索引,直到找到
null
条目。如果您确实需要做这样的事情,您可能应该使用
List
而不是数组。You will need to loop through all indices of the array till you find a
null
entry.If you really need to do something like this, you should probably be using a
List<string>
and not an array.忽略你这样做的原因 - 其他人都告诉过你关于
List
- 在下面的代码中,lowest
等于 2。Ignoring why you are doing this - everyone else has told you about
List<string>
- in the below code,lowest
is equal to 2.为此使用通用列表:
在大多数情况下,您可以像数组一样使用列表,包括通过下标访问成员。
Use a generic list for this:
You can use a list in most cases just like an array, including access members by subscript.
当您创建
string[]
的新实例时,其条目为null
。现在您只需迭代数组,直到找到第一个
null
条目。根据您的问题,
List
实例可能会更好。在那里,您可以使用其
Add
方法将字符串附加到最后一个位置,无需自己处理列表长度。
如果您需要一个数组作为最终结果,则
ToArray
方法会派上用场。When you create a new Instance of
string[]
, its entries arenull
.Now you just need to iterate through the array until you find the first
null
entry.Depending on your problem a
List<string>
instance might be better.There you can just use its
Add
method to append a string to the last position,without the need to handle the list length yourself.
And if you need an array as the final result, the
ToArray
method comes in handy.在 C# 中使用数组时,您确实不必编写这样的代码。您最好将字符串存储在
List
(或许多其他方便的集合)中,该集合基本上是为随机访问元素而设计的。当您需要实际的字符串数组时,请在List
集合上调用.ToArray()
。You really shouldn't ever have to write code like this when working with an array in C#. You're better off storing your strings in a
List<String>
(or a number of other handy collections), which is designed for essentially random access to elements. When you need an actual array of strings, call.ToArray()
on yourList
collection.考虑使用
List
来代替,这样您可以轻松添加元素。拥有一个带有一些 null 的数组稍后会返回给您,您将再次检查 null...此外,附加这种方式需要时间,确实该数组很小(youiu 说 10 个元素),但无论如何您都会花费 cpu 周期每次都进行线性搜索。我认为可以尝试改进设计。Consider to use a
List<string>
instead, that easily allow you to add elements. Having an array with some null will come back to you later, and you will again check for null... Furtrhermore appending thsat way takes time, is true that the array is small ( yoiu said 10 elements ) but anyway you will spent cpu cycles doing a linear search every time. I think it is possible to try improve the design.