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 30 years of experience in information systems and software development for the industry. He is Senior Controls Engineer at OTTO Motors
He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).
Yvan draws on experience as owner of Red Cell Innovation Inc.
, 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), TinyMCE