Found this Post and it has good solution when shuffling items in List<T>
.
But in my case i have a class Person
which is defined as this:
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
This is my implementation and usage:
List<Person> workers = new List<Person>()
{
new Person { Id = 1, Name = "Emp 1", Position = "Cashier"},
new Person { Id = 2, Name = "Emp 2", Position = "Sales Clerk"},
new Person { Id = 3, Name = "Emp 3", Position = "Cashier"},
new Person { Id = 4, Name = "Emp 4", Position = "Sales Clerk"},
new Person { Id = 5, Name = "Emp 5", Position = "Sales Clerk"},
new Person { Id = 6, Name = "Emp 6", Position = "Cashier"},
new Person { Id = 7, Name = "Emp 7", Position = "Sales Clerk"}
};
Now i want to shuffle all records and get 1 Sales Clerk. Here is my code and is working:
var worker = workers.OrderBy(x => Guid.NewGuid()).Where(x => x.Position == "Sales Clerk").First();
// This can yield 1 of this random result (Emp 2, Emp 4, Emp 5 and Emp 7).
Console.WriteLine(worker.Name);
But according to the given Post GUID is not good for randomizing record. And the worst is i cant use Shuffle()
and call the Where
and First()
extensions to get the desired result.
How can i do that with Shuffle()
extension?