生成随机单词

时间:2012-09-05 10:30:56

标签: c# c#-4.0 c#-3.0 c#-2.0

apple,mango,papaya,banana,guava,pineapple - 如何使用c#随机(逐个)生成这些单词?请帮我从我的单词列表中随机生成单词..

4 个答案:

答案 0 :(得分:5)

Random rnd = new Random();
string GetRandomFruit()
{
    string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
    return fruits[rnd.Next(0,fruits.Length)];
}

答案 1 :(得分:3)

你可以随机排序"使用LINQ的OrderBy方法并使用Guid s

var words = new [] {"apple", "mango", "papaya", "banana", "guava", "pineapple"};
var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid());

foreach(var word in wordsInRandomOrder)
{
    Console.WriteLine(word);
}

以下foreach会以随机顺序从words数组中为您提供每个项目

答案 2 :(得分:3)

您可以使用Fisher-Yates来对阵列进行随机播放:

static class ArrayMethods
{
    private static readonly Random rng = new Random();
    public static void Shuffle<T>(IList<T> list)
    {
      var r = rng;
      var len = list.Count;
      for(var i = len-1; i >= 1; --i)
      {
          var j = r.Next(i);
          var tmp = list[i];
          list[i] = list[j];
          list[j] = tmp;
      }

    }
}

如下:

var arr = new[]{
  "apple", 
  "mango", 
  "papaya", 
  "banana", 
  "guava", 
  "pineapple"
};
ArrayMethods.Shuffle(arr);
foreach(var item in arr)
    //print 'em out

答案 3 :(得分:2)

您可以编写以下代码。

string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
Console.WriteLine(fruits[new Random().Next(0, fruits.Length)]);