Microsoft has expanded the System.Random class in .NET 8.0 to include new static functions.
Advertisement
Dr. Holger Schwichtenberg is the technical director of the expert network www.IT-Visions.de, which, with 53 renowned experts, supports numerous medium-sized and large companies through consulting and training as well as with software development. Through his appearances at numerous national and international conferences as well as more than 90 specialist books and more than 1,500 specialist articles, Holger Schwichtenberg is one of the best-known experts for .NET and web technologies in Germany.
Random.Shared.Shuffle() randomly sorts a given set. An object set of type System.Array or System.Span can be passed
CUI.H2(“Random order of numbers 1 to 20”); int[] zahlen = Enumerable.Range(1, 20).ToArray();
Console.WriteLine(“Vor Shuffle: ” + String.Join(‘;’, zahlen));
Random.Shared.Shuffle
Console.WriteLine(“After Shuffle: ” + String.Join(‘;’, numbers)); CUI.H2(“nRandom order of strings”); Span
“dotnettraining.de”, “www.dotnetframework.de”,
“www.dotnet8.de”, “dotnet-lexikon.de”,
“www.dotnet-doktor.de”,
“www.powershell-schulungen.de”]; Random.Shared.Shuffle(Sites); // 2. Overload: span
foreach (string site in Websites)
{
CUI.LI(site);
}
Output of the code sample for Random.Shared.Shuffle()
(Bild: Screenshot (Holger Schwichtenberg))
Random.Shared.GetItems() returns a random selection from a set. Here you can use an array or a ReadonlySpan
Span
“dotnettraining.de”, “www.dotnetframework.de”,
“www.dotnet8.de”, “dotnet-lexikon.de”,
“www.dotnet-doktor.de”,
“www.powershell-schulungen.de”]; CUI.H2(“Random 3×3”); for (int i = 0; i
//ReadOnlySpan
//ReadOnlySpan
string[] Random3 = Random.Shared.GetItems(Websites.ToArray(), 3); foreach (string site in random3) { CUI.LI(site); } Console.WriteLine(); }
Code example output from Random.Shared.GetItems()
(Bild: Screenshot (Holger Schwichtenberg))
(rme)
To home page