Summit
Summit

Reputation: 2268

How to remove elements from list using a condition

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.

Upvotes: 0

Views: 1409

Answers (3)

Petyor
Petyor

Reputation: 404

Try this:

listString.RemoveAll(x => Char.IsDigit(x[0]));

Upvotes: 4

Idle_Mind
Idle_Mind

Reputation: 39122

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

Upvotes: 1

IllusiveBrian
IllusiveBrian

Reputation: 3204

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.

Upvotes: 3

Related Questions