I have such a problem.
I sorted all the numbers in the list and printed them in the listBox. I read the numbers from the txt file which I make an array.
I need the user to type in any number (which I kept in the variable "a") those numbers in the following order:
- first the numbers less than a
- then the numbers equal to a
- and finally the big numbers.
and print it all in listBox.
...
float x;
if (float.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out x))
{
lst.Items.Add(x);
}
List<float> array = new List<float>();
array.Add(x);
a = Convert.ToInt32(txt1.Text);
int at = lst2.Items.Count;
for (int o = 0; o < lst2.Items.Count; o)
{
if (x < (float)(lst2.Items[o]) && a >= o)
{
at = o;
break;
}
}
lst2.Items.Insert(at, x);
With this code I only sort the numbers without sorting with a variable.
CodePudding user response:
You can just get the numbers which are less than, equal to, and greater than a
, then populate the ListBoxes.
private List<float> numbers = new List<float>();
private void Form1_Load(object sender, EventArgs e)
{
numbers = File.ReadAllLines("input.txt").Select(s => float.Parse(s)).ToList();
}
private void button1_Click(object sender, EventArgs e)
{
if (float.TryParse(txt1.Text, NumberStyles.Number, CultureInfo.InvariantCulture, out float a))
{
// add a to numbers?
numbers.Add(a);
var lessThan = numbers.Where(n => n < a);
var equalTo = numbers.Where(n => n == a);
var greaterThan = numbers.Where(n => n > a);
// populate listboxes?
lst.DataSource = lessThan.ToList();
lst1.DataSource = equalTo.ToList();
lst2.DataSource = greaterThan.ToList();
}
}
input.txt
123.45
1.2345
0.12345
12345
12.345
1234.5
If you want them all sorted, you can OrderBy when reading from the file
numbers = File.ReadAllLines("input.txt").Select(s => float.Parse(s)).OrderBy(n => n).ToList();