我需要帮助调整此代码以从.txt文件加载,并从中随机选择一行

时间:2016-12-14 19:23:16

标签: c#

代码的目的是使其从.txt文件加载,然后随机加载一行以显示。我摆弄它,我需要更多的帮助。任何帮助,将不胜感激。它被评论在哪里需要调整。

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

namespace EquityPicks
{
    public partial class MainForm : Form
    {
        public List<string> appList = new List<string>(7);

        public MainForm()
        {
            InitializeComponent();
            loadList();
        }

        public void loadList() // Adjust to load from a text File
        {
            appList.Clear();
            for(int i =0; i<10; i++)
            {
                string text;
                using (var streamReader = new StreamReader(@"c:\file.txt", Encoding.UTF8))
            {
                text = streamReader.ReadToEnd();
            }
            }

            nextUpTextBox.Text = getMember();
            onDeckTextBox.Text = getMember();
            studentsLeftTextBox.Text = appList.Count.ToString();
        }

        public string getMember() // Adjust for Randomness
        {
            string member = appList[0];
            appList.RemoveAt(0);
            return member;
        }

        void NextButtonClick(object sender, EventArgs e)
        {
            if(appList.Count >= 1)
            {
                nextUpTextBox.Text = onDeckTextBox.Text;
                onDeckTextBox.Text = getMember();
            }
            else if (appList.Count == 0)
            {
                nextUpTextBox.Text = onDeckTextBox.Text;
                onDeckTextBox.Text = "";
            }
            else
            {
                nextUpTextBox.Text = "";
                onDeckTextBox.Text = "";
            }
            studentsLeftTextBox.Text = appList.Count.ToString();
        }

        void ResetButtonClick(object sender, EventArgs e)
        {
            loadList();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我会用:

string[] array = File.ReadAllLines("path");

然后可以使用:

new Random().Next(int minValue, int maxValue)

从数组中选择一行。

编辑:澄清

maxValue应为&lt; = array.Length