How to select 4 random values from ListBox in ASP.Net

Last Reply on Jun 29, 2016 04:49 AM By Shashikant

Posted on Jun 28, 2016 02:01 AM

Hii,

How can we write code for select random item, from listbox when the listbox contains 10 or more items?

It should return always a different random item whenever the program is executed.

Posted on Jun 29, 2016 04:49 AM

Hi,

Please refer below code.

C#

public List<string> RandomizeList(List<string> originalList)
{
    List<string> randomList = new List<string>();
    Random random = new Random();
    string value = default(string);
    while (originalList.Count() > 0)
    {
        var nextIndex = random.Next(0, originalList.Count());
        value = originalList[nextIndex];
        randomList.Add(value);
        originalList.RemoveAt(nextIndex);
    }
    return randomList;
}

and you can take 4 only