Nameismy
Nameismy

Reputation: 152

Creating random Numbers, store them in array and sort them in two listboxes c#

I am trying to generate random int numbers, once I Generate them I want to store them in a listBox, after this sort them in second listBox. The code that I have:

        int Min = 0;
        int Max = 6;

        // this declares an integer array with 5 elements
        // and initializes all of them to their default value
        // which is zero
        int[] test2 = new int[6];

        Random randNum = new Random();
        for (int i = 1; i < test2.Length; i++)
        {
            test2[i] = randNum.Next(Min, Max);    
        }
        arrayListbox.ItemsSource = test2;
        Array.Sort(test2);
        foreach (int value in test2)
        {
            arrayListboxOrder.ItemsSource = test2;
        }

Upvotes: 1

Views: 981

Answers (2)

rbianchi
rbianchi

Reputation: 103

        int Min = 0;
        int Max = 6;
        // this declares an integer array with 5 elements
        // and initializes all of them to their default value
        // which is zero
        //int[] test2 = new int[6];

        arrayListboxOrder.ItemsSource = Enumerable.Range(Min, Max).OrderBy(x => Guid.NewGuid()).Take(5).OrderBy(n=>n).ToArray();

I saved a snippet here: http://rextester.com/GBM61947

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063058

The ItemsSource needs to be a different array - otherwise they both fundamentally have the same data. Sort one, sort them "both".

Try:

arrayListbox.ItemsSource = test2;
int[] sorted = (int[])test2.Clone();
Array.Sort(sorted);
arrayListboxOrder.ItemsSource = sorted;

Upvotes: 1

Related Questions