如何从此列表中访问随机项?

时间:2015-03-13 16:37:42

标签: c#

我创建了下面的列表,但现在我想从中访问一个随机项目,我该怎么做呢?

query = "SELECT id FROM booking WHERE haggle_Remaining>0 AND " +
    "(status='Allocated' OR status='Customer Rejected')";
haggleList = new List<JobComponent.JobList>();
using (var cmd = new MySqlCommand(query, DbObject.Connection))
{
    if (DbObject.Connection.State != ConnectionState.Open)
    {
        DbObject.OpenConnection();
    }
    try
    {
        using (MySqlDataReader dataReader = cmd.ExecuteReader())
        {
            while (dataReader.Read())
            {
                var item = new JobComponent.JobList
                {
                    JobId = dataReader["id"] + "",
                };
                haggleList.Add(item);
            }
            dataReader.Close();
            DbObject.CloseConnection();
        }
    }
    catch (Exception ex)
    {
        ErrorHandlingComponent.LogError(ex.ToString());
        throw;
    }
}

1 个答案:

答案 0 :(得分:0)

Random Rnd = new Random();
var jobItem = haggleList.ElementAt(Rnd.Next(1, haggleList.Count()));
var selectedJobId = Convert.ToInt32(jobItem.JobId);