littlefish
littlefish

Reputation: 25

Delete all elements in array apart from certain ones

So I have an array (string[]) and I have an array with the number of lines I wish to keep, is there a specific way to have it remove all but these, or maybe copy these into an empty array ?

This is the array with the line numbers

            for (int i = 0; i < dumpFile.Length; i++)
            {
                if (dumpFile[i].StartsWith(@"     ""videoId"":"))
                {
                    arrayIndex.Add(i);
                    string stringI = i.ToString() + "\r\n";
                    System.IO.File.AppendAllText("lines.txt", stringI);                       
                }
            }

Upvotes: 0

Views: 203

Answers (1)

degant
degant

Reputation: 4981

Using Linq:

To keep only certain elements in an array you can use the below code. Feel free to specify your condition in place of line.StartsWith(). You can also save these to a file like you were doing using a single statement instead of a loop.

string[] selected = dumpFile.Where(line => line.StartsWith(@"     ""videoId"":")).ToArray();

// Now saving these lines to a file in a single line instead of using a loop
System.IO.File.AppendAllLines("lines.txt", selected);

Upvotes: 3

Related Questions