C#中数组的子集 [英] Subset of Array in C#
问题描述
如果我有一个包含 12 个元素的数组,并且我想要一个包含第一个和第 12 个元素的新数组.例如,如果我的数组如下所示:
If I have an array with 12 elements and I want a new array with that drops the first and 12th elements. For example, if my array looks like this:
__ __ __ __ __ __ __ __ __ __ __ __
a b c d e f g h i j k l
__ __ __ __ __ __ __ __ __ __ __ __
我想转换它或创建一个看起来像
I want to either transform it or create a new array that looks like
__ __ __ __ __ __ __ __ __ __
b c d e f g h i j k
__ __ __ __ __ __ __ __ __ __
我知道我可以通过迭代它们来做到这一点.我只是想知道 C# 中是否有更简洁的方法.
I know I can do it by iterating over them. I was just wondering if there was a cleaner way built into C#.
**更新以修正错误.将 10 个元素更改为 12 个元素.
**UPDATED TO FIX A TYPO. Changed 10 elements to 12 elements.
推荐答案
LINQ 是您的朋友.:)
LINQ is your friend. :)
var newArray = oldArray.Skip(1).Take(oldArray.Length - 2).ToArray();
当然比手动创建数组并对其进行迭代效率低一些,但要简单得多...
Somewhat less efficient than manually creating the array and iterating over it of course, but far simple...
使用 Array.Copy
的稍微长一点的方法 如下.
The slightly lengithier method that uses Array.Copy
is the following.
var newArray = new int[oldArray.Count - 2];
Array.Copy(oldArray, 1, newArray, 0, newArray.Length);
这篇关于C#中数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!