net8 随机数类Random GetItems() 、Shuffle()方法

1、在 8 中对随机数类 Random 提供了 GetItems() 方法,可以根据指定的数量在提供的一个集合中随机抽取数据项生成一个新的集合:

ReadOnlySpan<string> colors = new[]{"Red","Green","Blue","Black"};
string[] t1 = Random.Shared.GetItems(colors, 10);
Console.WriteLine(JsonSerializer.Serialize(t1));
//输出:["Black","Green","Blue","Blue","Green","Blue","Green","Black","Green","Blue"]
//每次都会不一样
Console.ReadKey();

2、通过 Random 提供的 Shuffle() 方法,可以将一个集合中的数据项的顺序打乱:

string[] colors = new[]{"Red","Green","Blue","Black"};
Random.Shared.Shuffle(colors);
Console.WriteLine(JsonSerializer.Serialize(colors));
Console.ReadKey();

 

posted @ 2024-01-29 09:46  ziff123  阅读(57)  评论(0编辑  收藏  举报