0

This is the string i am adding to a list

 1 The first line\n
   The Second line\n
   The Third Line\n
 3 The fourth Line\n
 List<string> listString;
 listString = data.Split('\n').ToList();

Now from this list i want to remove those elements which start with a number.

Currently loop over the list and remove those elements which start with a number.

is this the only way or we can do it in much better way as the list has a very big size.

Summit
  • 2,112
  • 2
  • 12
  • 36

3 Answers3

4

Try this:

listString.RemoveAll(x => Char.IsDigit(x[0]));
Petyor
  • 389
  • 3
  • 12
3

Your best bet for efficiency is probably to do both operations while reading the string. Borrowing some code from this answer:

List<string> lineString = new List<string>();
using (StringReader reader = new StringReader(data))
{
    string line;
    do
    {
        line = reader.ReadLine();
        if (line != null && line.Length > 0 && !Char.isDigit(line.First()))
        {
            lineString.add(line);
        }

    } while (line != null);
}

A dedicated state machine to read the string character by character would possibly be slightly more efficient, if you still need the code to be more performant.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
1

On the off chance that a line could start with a NEGATIVE integer?

string data = "-12 The first line\n" +
                "The Second line\n" +
                "The Third Line\n" +
                "34 The fourth Line\n";


List<string> listString = new List<string>(data.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

Console.WriteLine("Before:");
listString.ForEach(x => Console.WriteLine(x));

listString.RemoveAll(x => Int32.TryParse(x.Split()[0], out int tmp));

Console.WriteLine("After:");
listString.ForEach(x => Console.WriteLine(x));
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40