0

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"}

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It should be noted that newArray is not an array, it's an IEnumerable<string>. This may be acceptable (it also avoids creating a new array). If the OP wants an actual array, they can use ToArray() to create one.
2

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();

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.