Introduction: In this article I am going to explain how to get n
random numbers from list of numbers in asp.net c# using LINQ.
In previous articles i explained Difference between IEnumerable and IQueryable in c# with example and Get checkboxlist selected items in comma separated format in asp.net(c#,vb) and Convert generic list to datatable in asp.net c#,vb and Jquery UI autocomplete textbox with database inasp.net c#,vb with example and Validate,upload,crop and store image in folder in asp.net using jquery
In previous articles i explained Difference between IEnumerable and IQueryable in c# with example and Get checkboxlist selected items in comma separated format in asp.net(c#,vb) and Convert generic list to datatable in asp.net c#,vb and Jquery UI autocomplete textbox with database inasp.net c#,vb with example and Validate,upload,crop and store image in folder in asp.net using jquery
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();
}
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.
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..