I recently looked at some code that pulled a bunch of news items from a SharePoint list and displayed them in random order. The code was a little verbose, so I changed it to use the System.Data.DataSetExtension helper methods. The final code looked something like this:
//Perform the normal SPQuery SPQuery query = new SPQuery(); // query options left for reader to insert //the list variable is a reference to the SharePoint list you want to query DataTable data = list.GetItems(query).GetDataTable(); Random rnd = new Random(); //Randomize the items using LINQ and some helper methods from System.Data.DataSetExtension DataTable items = data.AsEnumerable().OrderBy((i) => (r.Next()));
The other nice thing about using the Random class is its flexibility to offer some other cool features. Just say you wanted to show the same random items all day, then it’s just a matter of seeding with the current day.