简体   繁体   English

按随机字母顺序排序列表

[英]Sort List in Random Alphabetical Order

I have a class Tester , where the definition is我有一个 class Tester ,定义是

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 . ,我被要求实现一种方法来按TaskCount的升序对Tester对象列表进行排序。

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:例如,我在列表中有 3 个Tester对象: new Tester("A", 1)new Tester("B", 5)new Tester("C", 1) ,如果我只使用默认的OrderBy方法按TaskCount对它们进行排序,列表将始终如下所示:

A (TaskCount: 1)
C (TaskCount: 1)
B (TaskCount: 5)

because in alphabetical order, the letter 'A' always comes before 'C'.因为按字母顺序,字母“A”总是在“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 ?有没有办法让我按随机字母顺序对列表进行排序,同时它仍然按TaskCount的升序排列,所以结果看起来像ACB的可能性为 50%,而结果看起来像CAB的可能性为 50%? Thank you in advance!先感谢您!

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. OrderBy 会将 Tester 实例放入 TaskCount 顺序,ThenBy 将随机化那些具有相同 TaskCount 值的实例。

Note - the original ordering of A, C, B was not due to alphabetic order of Name, but order of insertion into the list.注意 - A,C,B 的原始排序不是由于名称的字母顺序,而是插入列表的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM