在C#中数组的子集 [英] Subset of Array in C#

查看:1269
本文介绍了在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#.

**更新到FIX一个错字。改变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...

这是使用的稍微lengithier方法 Array.Copy 如下。

The slightly lengithier method that uses Array.Copy is the following.

var newArray = new int[newArray.Count - 2];
Array.Copy(oldArray, 1, newArray, 0, newArray.Length);

这篇关于在C#中数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆