Every now and again, there is a need to produce a list in a random order. 

I've found a very reliable way to do this using linq and the Guid class.

It might sound complicated, but when you see the example, it should make sense and you should see how simple it is.

using System;
using System.Collections.Generic;
using System.Linq; namespace PaulSeal.Library.Utility
class Example
public List<int> GetRandomListOfNumbers()
List<int> results = new List<int>() { 1, 2, 3, 4, 5, 6 };
var sortedResults = from r in results orderby Guid.NewGuid() ascending select r;
return sortedResults.ToList();

On the first line, we create the list of results which is in ascending order.

Then we select each record from the results, ordered by a new Guid each time. This is what gives the randomness.

Finally we return the list.

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

Buy me a coffee

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to render the actual document type icons in the tree in Umbraco

This post gives you the code to be able to see the icons for your document types in the tree view ra…

Read Post

Code to help you debug an umbraco issue on a remote site

This post gives you some razor code to help you see the values of the IPublishedContent item's prope…

Read Post

How to fix corrupt accented characters in Excel for a C# export as CSV

This post will help you fix the issue where you csv export has corrupt characters when opening it in…

Read Post

How to include scripts from partial views in MVC and Umbraco

This post will show you how you can include scripts from inside an MVC partial view rather than havi…

Read Post