如何从字符串创建随机名称接受者并使其不重复?在C#中 [英] How do I create a random name taker from an string and make it non-repeated? in C#

查看:99
本文介绍了如何从字符串创建随机名称接受者并使其不重复?在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我......

我需要创建一个从字符串(或数组,或任何可能有用的)获取名称并显示它的应用程序。加上显示一个名称时,不应再显示。 (顺便说一下,字符串中会有35个名字)。

提前感谢您的所有答案......

解决方案

To避免重复,只需重复获取随机值,直到获得新的唯一值。如何快速检查每一步的唯一性?使用类 System.Collections.Generic.HashSet<>

https://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx [ ^ ],

https:// msdn .microsoft.com / zh-CN / library / bb356440%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/bb353005%28v=vs.110%29.aspx [ ^ ]。



重复生成直到包含返回ns false,然后将值添加到哈希集,以及其他需要唯一值的地方。



-SA


假设这些名称都存储在数组0..34中。

随机获取它们如下 -

随机r = 随机(Guid.NewGuid()。GetHashCode()); 
Console.WriteLine(nameArray [r.Next( 0 35 ))];


Please help me...
I need to create an application that takes names from a string (or array, or whatever might be useful) and display it. plus when one name is displayed it should not shown again. (by the way there will be 35 names in the string).
Thanks in advance for all your answers...

解决方案

To avoid repetitions, simply repeat getting the random value until you get a new unique value. How to quickly check up uniqueness on each step? Use the class System.Collections.Generic.HashSet<>:
https://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/bb356440%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/bb353005%28v=vs.110%29.aspx[^].

Repeat generation until Contains returns false, then Add the value to the hash set, and elsewhere, where you need the unique value.

—SA


Lets say these names are all stored in an array 0..34.
Get them randomly as follows -

Random r = new Random(Guid.NewGuid().GetHashCode());
Console.WriteLine(nameArray[r.Next(0, 35))];


这篇关于如何从字符串创建随机名称接受者并使其不重复?在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆