List.Remove 全部不从文本文件中删除负数

List.Remove All not removing the negative numbers from textfile

这就是我希望此代码执行的操作。

  1. 将文本文件 random.txt 读入列表
  2. 对于读入列表的文本文件的每一行,我想使用带有 lambda 表达式的 .RemoveAll 来确定它是正数还是负数。
  3. RemoveAll 应该删除包含负数的每一行
  4. 我想把修改后的列表显示成列表框显示

我不能使用 Linq,我必须使用 ListMethod RemoveAll。

'''''

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using System.IO;

 namespace meade_13_1
 {
  public partial class Form1 : Form
 {

    public Form1()
    {
        InitializeComponent();

    }
    private void btnFindAll_Click(object sender, EventArgs e)
    {
       
    }

    private void btnRemoveNeg_Click(object sender, EventArgs e)
    {
        List<int> list = new List<int>();
        using (StreamReader reader = new StreamReader("random.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                list.Add(Int32.Parse(line));
                
                
            }
        }
        list.RemoveAll(x => x > 0);
        listBox1.Items.Add(list);

         }
     }
 }

'''''

与其直接使用 readerlist,我建议 queryingLinq:

的帮助下
using System.Linq;

...

private void btnFindAll_Click(object sender, EventArgs e) {
  var items = File
    .ReadLines("random.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(line => double.Parse(line)) //TODO: int.Parse if item is int
    .Where(item => item > 0); 

  foreach (var line in items) 
    listBox1.Items.Add(line);        
}

为了安全起见,我在这里添加了 .Where(line => !string.IsNullOrWhiteSpace(line)) - 我忽略了可能的空行

它不会删除负数,因为您传递给 RemoveAll 的 lamda 表达式用于过滤正数。对于底片,它应该是 x => x < 0.

所以如果你需要没有Linq的版本,我可以提出两个方案:

  1. 根本没有列表(只向列表框添加正数)
using (StreamReader reader = new StreamReader("random.txt"))
{
   string line;
   while ((line = reader.ReadLine()) != null)
   {
    if (int.TryParse(line, out int number) && number >= 0)
       listBox1.Items.Add(number);
   }
}
  1. 有列表和RemoveAll
var numbers = new List<int>();
using (StreamReader reader = new StreamReader("random.txt"))
{
   string line;
   while ((line = reader.ReadLine()) != null)
   {
     if (int.TryParse(line, out int number)
       numbers.Add(number);
   }
   numbers.RemoveAll(n => n < 0);
   foreach (int num in numbers)
     listBox1.Items.Add(num);
}

顺便说一下,对于这种任务,File.ReadLines 更自然(因为即使方法名称也说明这正是我们需要的):

foreach (string line in File.ReadLines("random.txt")
{
  if (int.TryParse(line, out int num) && num >= 0)
     listBox1.Items.Add(num);
}