Select or generate n random numbers / items from list in Asp.net C#

Description: While working on project i got the requirement to get n random numbers from list. I was able to get this requirement fulfilled very easily using LINQ. I am going to share this with all so that it might help me and others in future. 


Implementation: Let’s understand by an example. 

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
        List<int> randomNumberList = new List<int>();
        randomNumberList = GetRandomElements(list, 3);
    }

  public List<t> GetRandomElements<t>(IEnumerable<t> list, int elementsCount)
    {
        return list.OrderBy(x => Guid.NewGuid()).Take(elementsCount).ToList();
    }

On first run it produced result as:


get random numbers or items from list od numbers in asp.net C#


On second runt the result was:


get random numbers or items from list od numbers in asp.net C#

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..