简体   繁体   中英

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

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. Also, the code above, will return the whole array if the search for the string is unsuccessful.

You can use Linq's 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.

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.

there is another simple way to do that using arrayList:

you can use method 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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