如何从数组中选择一个随机元素

时间:2012-10-22 10:18:48

标签: c# arrays random

我正在尝试从字符串数组中选择一个随机元素并将其保存在我的数据库中。

OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string Update = string.Format("UPDATE Ships SET InPort=True");
OleDbCommand myCommandUpdt = new OleDbCommand(Update);
myCommandUpdt.Connection = myConnection;
myCommandUpdt.ExecuteNonQuery();
OleDbDataReader drdrShipsRead = myCommandUpdt.ExecuteReader();

string[] Randominporta = { "True", "False", "False" };
// Testlabel.Text = Convert.ToString(Randominport[randomNumber]);

int iNumber = 1;
while (drdrShipsRead.Read())
{
    int randomNumber = random.Next(0, 3);
    string myAddingQuery = string.Format(" UPDATE Ships SET InPort= " + Convert.ToString(Randominport[randomNumber]) + " WHERE ID= " + iNumber + "");
    OleDbCommand myCommand = new OleDbCommand(myAddingQuery);

   string myCommand.Connectionresult = myConnection;
    myCommand.ExecuteNonQuery();
    iNumber++;
}

它不起作用。

3 个答案:

答案 0 :(得分:2)

这样做的简单方法是:

var a = new List<string> { "True", "False", "False" };

int index = random.Next(strings.Count);
var name = a[index];
a.RemoveAt(index);
return name;

答案 1 :(得分:1)

感谢@CodesInChaos,我认为问题中的代码通常是正确的,但你没有正确声明你的数组,

尝试,

var randomImport = new [] { "True", "False", "False" };

这样做不那么脆弱

var randomImport = new [] { "True", "False", "False" };
var randomNumber = random.Next(0, randomImport.Length);

,或者

var randomNumber = random.Next(
    randomImport.GetLowerBound(0),
    randomImport.GetUpperBound(0) + 1);

答案 2 :(得分:0)

与Jodrell一起回答,您应修改以下行以包含SET InPort值的引号。

    string myAddingQuery = string.Format(" UPDATE Ships SET InPort= '" + Convert.ToString(Randominport[randomNumber]) + "' WHERE ID= " + iNumber + "");