I have a class Tester
, where the definition is
public class Tester
{
public string Name;
public int TaskCount;
public Tester(string name, int taskCount)
{
Name = name;
TaskCount = taskCount;
}
}
, and I am asked to implement a method to sort a list of Tester
objects by the ascending order of TaskCount
.
For example, I have 3 Tester
objects in the list: new Tester("A", 1)
, new Tester("B", 5)
, new Tester("C", 1)
, and if I just use the default OrderBy
method to sort them by TaskCount
, the list would always looks like:
A (TaskCount: 1)
C (TaskCount: 1)
B (TaskCount: 5)
because in alphabetical order, the letter 'A' always comes before 'C'. Is there a way for me to sort the list in random alphabetical order while it's still in ascending order of TaskCount
, so there's 50% chance that the result would look like ACB
and 50% chance be CAB
? Thank you in advance!
CodePudding user response:
You could use a Random number generator for subsequent ordering after the initial ordering.
List<Tester> lt = new List<Tester>();
lt.Add(new Tester("C", 1));
lt.Add(new Tester("B", 5));
lt.Add(new Tester("A", 1));
lt.Add(new Tester("D", 5));
Random r = new Random();
Console.WriteLine(lt.OrderBy(x => x.TaskCount).ThenBy(x => r.Next()));
The OrderBy will put the Tester instances into TaskCount order, the ThenBy will randomise those that have the same TaskCount value.
Note - the original ordering of A, C, B was not due to alphabetic order of Name, but order of insertion into the list.