在 C# 中按最后一个而不是第一个调整数组大小
我有一个 Class 元素数组,通过 int 变量,我需要将该数组的大小调整为最后 X 个元素。
例如,我有一个数组:
Array[0] = Msg1
Array[1] = Msg2
Array[2] = Msg3
Array[3] = Msg4
Array[4] = Msg5
Array[5] = Msg6
Array[6] = Msg7
Array[7] = Msg8
Array[8] = Msg9
Array[9] = Msg10
并且我只需要数组中的最后 8 个元素。
我无法使用 Array.Resize 函数,因为结果将是:
Array[0] = Msg1
Array[1] = Msg2
Array[2] = Msg3
Array[3] = Msg4
Array[4] = Msg5
Array[5] = Msg6
Array[6] = Msg7
Array[7] = Msg8
我需要这样的东西:
Array[0] = Msg3
Array[1] = Msg4
Array[2] = Msg5
Array[3] = Msg6
Array[4] = Msg7
Array[5] = Msg8
Array[6] = Msg9
Array[7] = Msg10
我怎样才能做到这一点?我希望我的问题很清楚。
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 LINQ:
不使用 LINQ:
With LINQ:
Wthout LINQ:
创建一个新数组,然后执行
Array.Copy()
。或者,使用 LINQ,您可以做到
array.Skip(array.Length - 8).Take(8).ToArray()
Create a new Array, then do
Array.Copy()
.Or, with LINQ, you can do
array.Skip(array.Length - 8).Take(8).ToArray()
它们的顺序必须相同吗?
像哎呀这样的东西怎么样
,你可以再次逆转以取回你的订单
Do they have to be in the same order?
How about something like
Heck, you could reverse again to get your order back
我认为您可能使用了错误的集合。从您的示例来看,它看起来像一个 队列 或 LinkedList 会更好选择,这两者都会使您的操作变得更加容易,甚至微不足道,并且自 2.0 以来两者都已成为 .NET FCL 的一部分。 (不需要专门的集合库。)
对于队列集合,您可以简单地调用 出队 n次,并且使用 LinkedList 您可以调用 RemoveFirst n 次为您提供最终结果。
除了修剪集合的开头之外,您还将使用其他 LinkedList 或 Queue 操作,这可能也很有用。
I think that you're probably using the wrong collection. From your example it looks like a Queue or a LinkedList would be better choices, both of which would make your operation much easier, even trivial AND both have been part of the .NET FCL since 2.0. (No need for a specialized collections library.)
For a Queue collection you could simply call Dequeue n-times and with a LinkedList you could call RemoveFirst n-times giving you your final result.
And besides trimming the beginning of the collection you will be using other LinkedList or Queue operations which will probably be useful as well.
许多采用数组作为参数的函数都有重载,这些重载采用附加参数,例如
startIndex
以及length
/count
或结束索引
。第二个参数有时是可选的,因为可以使用 Array.Length 属性推断出长度或 endIndex。例如:
或者
只是把这个扔出去;也许这是您的一个选择。
Many functions that take arrays as parameters have overloads that take additional parameters such as a
startIndex
along with either alength
/count
or anendIndex
. The second parameter is sometimes optional, since the length or endIndex can be inferred using theArray.Length
property.For example:
or
Just throwing this out there; perhaps this is an option for you.