Reputation: 3
I'm currently working on a calculator but 2 of my algorithms are not working correctly.
In my history (listbox) I get the numbers from the calculator and I have a bottom that finds the smallest number. I get an error with my code.
I want to have a [sorting] bottom that sorts the numbers ascending or descending. I've tried things as listbox1.sorted but I only get it to work as alphabetic.
If you know what I'm doing wrong with nr.1 or know how to fix a sorting algorithm please let me know.
int count = 0;
int tal = 0;
double Mtal = 999999999999999999;
bool hit;
int count1 = 0;
private void button26_Click(object sender, EventArgs e)
{
while (count < 100)
{
foreach (var Listboxitem in listBox1.Items)
{
hit = false;
if (Convert.ToDouble(Listboxitem) < Mtal)
{
Mtal = Convert.ToDouble(Listboxitem);
hit = true;
}
count = count + 1;
if (hit)
{
count1 = count;
}
}
}
this.listBox1.SelectedIndex = count1 - 1;
}
Upvotes: 0
Views: 77
Reputation: 711
Your values in ListBox are Integers. So change the declaration of your variable Mtal
from double
to int
. And then, instead of Convert.ToDouble()
use int.Parse()
, because you need integers for comparing to existing min value.
Something like this should work for you:
int count = 0;
int tal = 0;
int Mtal = int.MaxValue;
bool hit;
int count1 = 0;
private void button26_Click(object sender, EventArgs e)
{
while (count < 100)
{
foreach (var Listboxitem in listBox1.Items)
{
hit = false;
if (int.Parse(Listboxitem.ToString()) < Mtal)
{
Mtal = int.Parse(Listboxitem.ToString());
hit = true;
}
count = count + 1;
if (hit)
{
count1 = count;
}
}
}
this.listBox1.SelectedIndex = count1 - 1;
}
And then for Ordering I would suggest you to use LINQ on List<ListItem>
. For your example:
private void button_OrderByDescencing_Click(object sender, EventArgs e)
{
List<ListItem> items= new List<ListItem>();
foreach (ListItem a in lb.Items)
{
items.Add(a);
}
items=items.OrderByDescending(a => int.Parse(a.Value)).ToList();
foreach (ListItem a in items)
{
listBox1.Items.Add(a);
}
}
And for ascending:
private void button_OrderByAscending_Click(object sender, EventArgs e)
{
List<ListItem> items= new List<ListItem>();
foreach (ListItem a in lb.Items)
{
items.Add(a);
}
items= items.OrderBy(a => int.Parse(a.Value)).ToList();
foreach (ListItem a in items)
{
listBox1.Items.Add(a);
}
}
Upvotes: 2