Here's what I want this code to do.
I cannot use Linq, and I must use the 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);
}
}
}
'''''
It doesn't remove negative numbers simply because the lamda expression you pass to RemoveAll
is used to filter positive numbers. For negatives it should be x => x < 0
.
So if you need the version without Linq, I can propose two options:
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);
}
}
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);
}
And by the way for this kind of task the File.ReadLines
is more natural (because even the method name says that this does exactly what we need):
foreach (string line in File.ReadLines("random.txt")
{
if (int.TryParse(line, out int num) && num >= 0)
listBox1.Items.Add(num);
}