Shuffle objects list using by Linq Random
C# Shuffle List of Objects
Student Class
1 2 3 4 5 6 7 8 9 |
public class Student { string name; public Student(string name) { Name = name; } public string Name { get => name; set => name = value; } } |
Main Method: Shuffle with Linq
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 |
class Program { static void Main(string[] args) { List<Student> mylist = new List<Student>(); mylist.Add(new Student("JAMES")); mylist.Add(new Student("DAVID")); mylist.Add(new Student("PAUL")); mylist.Add(new Student("GEORGE")); mylist.Add(new Student("LARRY")); //shuffle var rnd = new Random(); var result = mylist.OrderBy(item => rnd.Next()); foreach (var item in result) { Console.WriteLine(item.Name); } Console.ReadLine(); } } |