Click here to Skip to main content
15,898,792 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends

I have one class

public class PollOptions:Polls
    {
        #region [ Constructors ]
        public PollOptions()
        {
        }
        #endregion

        #region [ Properties ]

        public Guid PollOptionsGuid { get; set; }
        public int AnswerNumber { get; set; }
        public string AnswerText { get; set; }
        public int Votes { get; set; }

        #endregion

        
    }


I have one method in another class which returns Array of PollOptions class.
For example
PollOptions[] options = obj.GetPollOptions(poll.PollGuid);


options array is in sort order by AnswerNumber value. I want to arrange this array in random order.

For example. Currently it is in order like as
1 Ans1
2 Ans2
3 Ans3
And I want to make it random sort order such as

3 Ans3
1 Ans1
2 Ans2

In any order but should be random every time.

Thanks
Imrankhan
Posted

I found code from google.

public PollOptions[] GetRandomOptions(PollOptions[] options)
    {
        int newIndex;
        PollOptions temp;
        for (int i = 0; i < options.Length; i++)
        {
            newIndex = new Random().Next(options.Length);
            temp = options[i];
            options[i] = options[newIndex];
            options[newIndex] = temp;
        }
        return options;
    }
 
Share this answer
 
So you want to randomize and array. Did you consider using the Random object? (Actually, there's a better random method but it's kind of limited (only returns 0 to 255), but at least it's built into the framework. In any case, the general approach you want to take is to

0) get a random number from 0 to array.Length - 1

1) retrieve the item at that index in array A

2) Remove the item from Array A

3) Add the item to array B

4) If array A isn't empty, go back to step 0

5) If array A *is empty, copy array B back to array A in its entirety

I leave it to you to actually come up with the actual code.

BTW, if you're going to be a programmer, you're going to have to learn how to come up with this kind of stuff on your own - seriously - this is pretty basic stuff.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900