I needed to randomize an enumerable collection. Here's what I came up with in the 60 seconds I thought it deserved.
- Do it better. better = faster with same number of items and/or faster with
- Prove it.
static class IEnumerableExtension
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> collection)
var list = new List<T>(collection);
var randomizer = new Random();
for (int i = list.Count; i > 0; i--)
int r = randomizer.Next(0, i);
yield return list[r];
Yvan Rodrigues has 25 years of experience in information systems and software development for the manufacturing sector. He runs Red Cell Innovation Inc.
/L'innovation de Globules Rouges
, a consulting company focusing on efficiency and automation of manufacturing and business processes for small businesses, healthcare, and the public sector. He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).
Yvan draws on experience at Mabel's Labels Inc.
as Manager of Systems and Development, and the University of Waterloo
as Information Systems Manager.
Yvan supports open-source software. He is a committer for SharpKit
(Issue/Ticket Management System), and contributes to MySQL, Ghostscript, iTextSharp, Bacula, FreeBSD, MonoTouch, and Mono for Android.
Yvan's consumer-focused apps can be found in the Windows Store, Apple App Store, and Google Play marketplace.