我正在将文件读入列表,然后想要一个按钮从列表中提取随机条目。我可以在VB中做到这一点,但对于c#来说还是比较新的。我知道我必须将名单公之于众,但我越来越感到沮丧。 下面的代码将文件读入列表,然后读取列表框。
namespace texttoarray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
var list = new List<string>();
var file = new StreamReader(@"list.txt");
while ((line = file.ReadLine()) != null)
{
list.Add(line);
counter++;
}
listBox2.DataSource = list;
var rnd = new Random();
}
}
}
答案 0 :(得分:0)
如果要在一个方法中处理某些信息并在另一个方法中使用此处理过的信息,您可以:
我会假设你的第二种方法,所以你可以这样做:
static class Program
{
// list inside your class with the information you need
private static List<string> fileLines;
private static void Main(string[] args)
{
// call the method to read your file and create the list
FirstMethod();
// second method to get a random line, in this case, will return the string
var result = SecondMethod();
Console.WriteLine(result);
Console.ReadLine();
}
private static void FirstMethod()
{
// with this approach you can load one line per string inside your List<>
var yourFile = File.ReadAllLines("C:\\test.txt");
fileLines = new List<string>(yourFile);
}
private static string SecondMethod()
{
// random number starting with 0 and maximum to your list size
var rnd = new Random();
return fileLines[rnd.Next(0, fileLines.Count)];
}
}