![](/img/trans.png)
[英]How to Remove elements from one List based another list's element and condition?
[英]How to remove elements from list using a condition
这是我要添加到列表中的字符串
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();
现在从这个列表中我想删除那些以数字开头的元素。
当前循环遍历列表并删除那些以数字开头的元素。
这是唯一的方法,还是我们可以用更好的方法来做,因为列表很大。
尝试这个:
listString.RemoveAll(x => Char.IsDigit(x[0]));
提高效率的最佳选择可能是在读取字符串时同时执行这两项操作。 从这个答案中借用一些代码:
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);
}
如果您仍然需要更高性能的代码,专用 state 机器逐个字符地读取字符串可能会更有效。
如果一行可能以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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.