|
|
#1 |
|
.NUT
Join Date: May 05
Location: Sydney, Australia
Posts: 60,536
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
(.NET 3.5) Randomise a List of Items
VB version here.
The following is an extension method for getting the contents of any IEnumerable(Of T) object, e.g. an array or List(Of T), in random order: Code:
using System;
using System.Collections.Generic;
using System.Linq;
public static class Enumerable
{
public static IEnumerable<T> Randomise<T>(this IEnumerable<T> items)
{
T[] result = null;
if (items != null)
{
var rng = new Random();
result = (from item in items
orderby rng.NextDouble()
select item).ToArray();
}
return result;
}
}
Code:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
foreach (var number in numbers.Randomise())
{
MessageBox.Show(number.ToString());
}
Note that you could write a regular method that does the same thing in earlier versions.
__________________
![]() 2007, 2008, 2009, 2010 Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs MSDN "How Do I?" Videos: VB | C# VBForums Database Development FAQ My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#) My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET Last edited by jmcilhinney; Sep 29th, 2009 at 08:57 PM. Reason: Simplified code |
|
|
|
|
|
#2 |
|
.NUT
Join Date: May 05
Location: Sydney, Australia
Posts: 60,536
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Re: (.NET 3.5) Randomise a List of Items
Note that I have simplified the code a little from the original. The new code will not throw an exception if you call it on a null reference but it will return a null reference. As such, an exception will be thrown if you try to enumerate the result, which did not happen with the old code. You could easily adjust the code to return an empty array if a null reference is passed in to avoid that if you think it's appropriate.
__________________
![]() 2007, 2008, 2009, 2010 Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs MSDN "How Do I?" Videos: VB | C# VBForums Database Development FAQ My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#) My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET |
|
|
|
|
|
#3 |
|
Frenzied Member
Join Date: Jul 08
Location: Rep of Ireland
Posts: 1,339
![]() ![]() |
Re: (.NET 3.5) Randomise a List of Items
Very nice use of extension methods jm!
|
|
|
|
![]() |
|
||||||
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|