Home » New in .NET 8.0 [11]: New random functions

New in .NET 8.0 [11]: New random functions

by admin
New in .NET 8.0 [11]: New random functions

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(pay); // 1. Overload: T[]
Console.WriteLine(“After Shuffle: ” + String.Join(‘;’, numbers)); CUI.H2(“nRandom order of strings”); Span Websites = [“www.IT-Visions.de”, “angular-schulungen.de”,
“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 hand over.

Span Websites = [“www.IT-Visions.de”, “angular-schulungen.de”,
“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 WebsitesReadOnly = Websites;
//ReadOnlySpan RandomSelect3 = Random.Shared.GetItems(WebsitesReadOnly, 3); // or array T[]
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

See also  The spectacular image of the 'hand of God' trying to reach the stars captured by the Inter-American Observatory

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy