【问题标题】:How could I get a random string from a list and assign it to a variable如何从列表中获取随机字符串并将其分配给变量
【发布时间】:2019-12-06 20:53:26
【问题描述】:

我的列表定义为:

List<string> firstNames = new List<string>();

当我向这个列表中添加一些字符串时,我将如何从列表中检索一个随机字符串?比如:

string currName = someFunctionOf (firstNames);

【问题讨论】:

  • 加分 - 做一个扩展方法来做到这一点!

标签: c#


【解决方案1】:

这里有一种与发布的三个不同的方法,只是为了让 LINQ 更加多样化和有趣:

string aName = firstNames.OrderBy(s => Guid.NewGuid()).First();

【讨论】:

  • -1 表示默默无闻,+1 表示聪明,+1 表示应用 SQL 技巧。
  • 我可能会提到这种方法难以阅读,速度慢,不应该在实际代码中使用。
  • @Eds 但很有趣也很聪明
【解决方案2】:

这样的?

List<string> myList = new List<string>( );
// add items to the list
Random r = new Random( );
int index = r.Next( myList.Count );
string randomString = myList[ index ];

【讨论】:

【解决方案3】:

试试这个

    List<string> firstNames = new List<string>();
    firstNames.Add("name1");
    firstNames.Add("name2");
    firstNames.Add("name3");
    firstNames.Add("namen");

    Random randNum = new Random();
    int aRandomPos = randNum.Next(firstNames.Count);//Returns a nonnegative random number less than the specified maximum (firstNames.Count).

    string currName = firstNames[aRandomPos];

【讨论】:

  • 应该是 int aRandomPos = randNum.Next(firstNames.Count - 1);否则,当随机数选择最大值时,您可能会得到索引超出范围异常。在 Yourcase 4
  • @Jebli 这不正确 - 它返回的随机数 小于 比最大值。所以randNum.Next(firstNames.Count); 按预期工作。
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 2013-05-09
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
相关资源
最近更新 更多