简体   繁体   中英

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.

Try this:

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

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.

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

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