简体   繁体   English

如何跳过数组中的前几个元素?

[英]How to skip first few elements from array?

I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further. 我有一个共有5000个元素的数组,在一个功能中,我只需要最后3000个元素才能继续进行。

for that I have tried following solution. 为此,我尝试了以下解决方案。

//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();

This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line. 这个解决方案实际上给了我想要的解决方案,但是当我在我的代码上运行profiler时,它在这一行显示了大量的内存分配。

I have to use Array only due to carried on legacy. 由于遗留下来,我必须使用Array。 and very frequent ToArray() doesn't seem to be good for performance. 并且非常频繁的ToArray()似乎对性能没有好处。

there is also possible solution, 还有可能的解决方案,

//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements) 
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);

but this is even worse in time complexity. 但是时间复杂度更差。

Is there any better solution for this, which doesn't need casting from List to Array ? 有没有更好的解决方案,不需要从List到Array?

If you absolutely have to use an array, then Array.Copy is probably your friend: 如果你绝对必须使用数组,那么Array.Copy可能是你的朋友:

int[] smallerArray = new int[array.Length - 2000];
Array.Copy(array, 2000, smallerArray, 0, smallerArray.Length);

I'd expect that to be a bit more efficient than using Take followed by ToArray . 我希望它比使用Take后跟ToArray更有效。

If list is a List<> you can use List.GetRange : 如果listList<>您可以使用List.GetRange

int lastN = 3000;
var sublist = list.GetRange(list.Count - lastN, lastN);
var array = sublist.ToArray();

This is more efficient because List.ToArray uses Array.Copy . 这更有效,因为List.ToArray使用Array.Copy


If list is an int[] as commented it's even more efficient: 如果list是一个注释的int[] ,它会更有效:

int lastN = 3000;
int[] result = new int[lastN];
Array.Copy(list, list.Length - lastN, result, 0, lastN); 

你可以使用Skip(提供你要排除的号码).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM