-1
我試圖讓這段代碼隨機選取4個鍵,然後使用'foreach'循環將它們寫入控制檯。它不是爲每次迭代挑選一個隨機選擇,而是隨機選擇一個鍵並將其寫入控制檯4次。這裏是代碼:爲什麼此方法只會隨機化一次,而不是隨機化每次迭代?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ListPractice
{
public class DictionaryData
{
public static void GetRandomKey()
{
Dictionary<string, int[]> QandA_Dictionary = new Dictionary<string, int[]>();
QandA_Dictionary.Add("What is 1 + 1?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 2?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 3?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 4?", new int[] { 2, 3, 4, 5 });
List<string> keys = new List<string>(QandA_Dictionary.Keys);
foreach (var element in keys)
{
Random rand = new Random();
string randomKey = keys[rand.Next(keys.Count)];
Console.WriteLine(randomKey);
}
Console.ReadKey();
}
public static void Main(string[] args)
{
GetRandomKey();
}
}
}
這是相當有趣。我仍在學習。謝謝你的幫助。 – sean
@sean:沒問題,我很高興能幫助你!還有更多信息需要閱讀[**有關它的MSDN文檔**](https://msdn.microsoft.com/en-us/library/h343ddh9(v = vs.110).aspx)。 –