C# || How To Shuffle & Randomize An Array/List/IEnumerable Using C#
The following is a module with functions which demonstrates how to randomize and shuffle the contents of an Array/List/IEnumerable using C#.
This function shuffles an IEnumerable and returns the results as a new List(Of T).
This function is generic, so it should work on IEnumerables of any datatype.
1. Shuffle – Integer Array
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize an integer array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Shuffle - Integer Array using Utils; var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; var results = numbers.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item}"); } // example output: /* 1991 1987 2009 22 28 2019 31 19 */ |
2. Shuffle – String List
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize a list of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Shuffle - String List using Utils; var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; var results = names.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item}"); } // example output: /* Jennifer Kenneth Sole Lynn */ |
3. Shuffle – Custom Object List
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize a list of custom objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// Shuffle - Custom Object List using Utils; public class Part { public string PartName { get; set; } public int PartId { get; set; } } var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; var results = parts.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // example output: /* 1334 - chain ring 1444 - banana seat 1434 - regular seat 1534 - cassette 1634 - shift lever 1234 - crank arm */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public static class Extensions { /// <summary> /// Shuffles an IEnumerable and returns the results as a List /// </summary> /// <param name="list">The IEnumerable list to shuffle</param> /// <returns>A List of shuffled items from the IEnumerable</returns> public static List<T> Shuffle<T>(this IEnumerable<T> list) { var r = new Random(); var shuffled = list.ToList(); for (int index = 0; index < shuffled.Count; ++index) { var randomIndex = r.Next(index, shuffled.Count); if (index != randomIndex) { var temp = shuffled[index]; shuffled[index] = shuffled[randomIndex]; shuffled[randomIndex] = temp; } } return shuffled; } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; using Utils; public class Program { public class Part { public string PartName { get; set; } public int PartId { get; set; } } static void Main(string[] args) { try { var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; var results = numbers.Shuffle(); foreach (var item in results) { Display($"{item}"); } Display(""); var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; var results1 = names.Shuffle(); foreach (var item in results1) { Display($"{item}"); } Display(""); var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; var results2 = parts.Shuffle(); foreach (var item in results2) { Display($"{item.PartId} - {item.PartName}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply