简体   繁体   English

从数组中删除元素,直到指定索引为止

[英]remove elements from array until specific index

I have a string array, I need to delete all elements until a specific index or get a new array of all elements from my specific index. 我有一个字符串数组,我需要删除所有元素,直到指定索引为止,或者从我的特定索引中获取所有元素的新数组。 I'm looking for a system function without loops. 我正在寻找没有循环的系统功能。 my code for example: 我的代码例如:

string []myArray = {"AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH"}
int myIndex = Array.IndexOf(myArray, "DDD");

needed output : 所需的输出:

string []myNewArray = {"EEE","FFF","GGG","HHH"}

Just use Skip in Linq 只需在Linq中使用Skip

string []myArray = {"AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH"}
int myIndex = Array.IndexOf(myArray, "DDD");
var newArray = myArray.Skip(myIndex+1);

Of course this means only that the loop is hidden from your view, but it exits nevertheless inside the Skip method. 当然,这仅意味着该循环从您的视图中隐藏了,但是仍然在Skip方法中退出。 Also, the code above, will return the whole array if the search for the string is unsuccessful. 另外,如果对字符串的搜索失败,则上面的代码将返回整个数组。

You can use Linq's SkipWhile 您可以使用Linq的SkipWhile

string[] myArray = { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH" };
var myNewArray = myArray.SkipWhile(x => x != "DDD").Skip(1).ToArray();

Arrays are a pretty "dumb" object, as they mostly just have methods that effectively describe themselves. 数组是一个非常漂亮的“哑”对象,因为它们仅具有有效描述自身的方法。 What you'll want to do is make it Queryable (one of its methods), then use LINQ to do it. 您要做的是使其成为可查询的(其方法之一),然后使用LINQ来实现。

string[] myarray = GimmeAStringArray();
int x = desiredIndexValue;

return myarray.AsQueryable().Where(t => myarray.IndexOf(t) > x);

You might not need to AsQueryable() it to do that. 您可能不需要AsQueryable()即可。

there is another simple way to do that using arrayList: 还有一种使用arrayList的简单方法:

you can use method arraylist.RemoveRange(start index, last index) 您可以使用方法arraylist.RemoveRange(start index, last index)

public static void Main()
{
  string[] array = new string[] {"AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH"};

  List<string> list = new List<string>(array);
  list.RemoveRange(0,list.IndexOf("DDD")+1);

  foreach (string str in list)
   {
    Console.WriteLine(str);
   }
}

output of program will be : 程序的输出将是:

EEE
FFF
GGG
HHH

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

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