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?

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 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

How to solve the error "Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0 ..."

This post will show you how to solve the error "Could not load file or assembly 'Microsoft.CodeDom.P…

Read Post

How to upload multiple files at once in an MVC form

This post will help you if you need to upload multiple files at once in an MVC form.  The examples…

Read Post