Reputation: 61
I am new to C# and I am trying to sort numbers from lowest to highest and then put them inside a ListBox
. What I did so far is:
{
int[] sortArray = new int[listBox2.Items.Count];
for (int i = 0; i < listBox2.Items.Count; i++)
{
string sort = listBox2.GetItemText(i);
sortArray[i] = int.Parse(sort);
}
int aantal = listBox2.Items.Count;
listBox2.Items.Clear();
Array.Sort(sortArray);
listBox2.Items.Add(sortArray);
}
There are some numbers in the ListBox
and when you press the button it should sort them. Can someone tell me what I do wrong?
Upvotes: 1
Views: 1075
Reputation: 61
I found the answer, this is what I had to do. Thanks for your help :)
int[] sortArray = new int[listBox2.Items.Count];
for (int i = 0; i < listBox2.Items.Count; i++)
{
sortArray[i] = Convert.ToInt16(listBox2.Items[i]);
}
int aantal = listBox2.Items.Count;
listBox2.Items.Clear();
Array.Sort(soorteerArray);
foreach (int value in sortArray)
{
listBox2.Items.Add(value);
}
Upvotes: 1
Reputation: 269
After you sort the array do this:
foreach(int number in sortarray)
listBox2.Items.Add(number);
Upvotes: 2
Reputation: 1646
I think you need to add the items individually.
{
int[] sortArray = new int[listBox2.Items.Count];
for (int i = 0; i < listBox2.Items.Count; i++)
{
string sort = listBox2.GetItemText(i);
sortArray[i] = int.Parse(sort);
}
int aantal = listBox2.Items.Count;
listBox2.Items.Clear();
Array.Sort(sortArray);
foreach(var i in sortArray)
listBox2.Items.Add(i);
}
Upvotes: 1
Reputation: 2989
I'm not in front of a computer with Visual Studio now to try it, but I think that something like this using Linq has to work
{
List<int> items = listBox2.Items.select(i => int.Parse(i)).ToList();
listBox2.Items.Clear();
listBox2.Items.Add(items.OrderBy(i => i).ToArray());
}
Upvotes: 1
Reputation: 947
Try this:
var newArray = sortArray.OrderByDescending(x => x).ToArray();
listBox2.Items.Add(sortArray);
Upvotes: 1