Reputation: 992
I have an app which selects a random word from a text file loaded into an array,
I currently do this:
.xaml:
<Label x:Name="GameWords" Text="Press 'Generate a Word' to get started" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
<Button x:Name="GenerateWord" Text="Generate a Word" Clicked="GetWord" />
xaml.cs:
async void GetWord(object sender, EventArgs e)
{
var WordsList = new List<string>();
using (var stream = await FileSystem.OpenAppPackageFileAsync("txtWords.txt"))
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
WordsList.Add(line);
}
}
string[] allWords = WordsList.ToArray();
var random = new Random();
int randNum = random.Next(1, 267751); /*Max lines in txtWords.txt */
string newWord = allWords[randNum];
GameWords.Text = newWord;
}
As you can see, every press of the button loads the entire file txtWords.txt (267751 words) into an array called allWords.
Ideally what I want to do is load the array once, probably on app load, then reference it in GetWord function. If I move the section of code where I load the array outside of the function, I can't seem to reference the array within GetWord?
What's the best way to structure my code to achieve this?
Upvotes: 1
Views: 60
Reputation: 13571
Your question is about code you aren’t sharing, making it hard to do anything other than provide an alternative implementation of the code you did share...
The code below is a minimal change to the code you shared to make it behave as you say you want it to. Note that it isn’t thread safe.
private static List<string> WordsList;
async void GetWord(object sender, EventArgs e)
{
if (WordsList == null) {
WordsList = new List<string>();
using (var stream = await FileSystem.OpenAppPackageFileAsync("txtWords.txt"))
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
WordsList.Add(line);
}
}
}
string[] allWords = WordsList.ToArray();
var random = new Random();
int randNum = random.Next(1, 267751); /*Max lines in txtWords.txt */
string newWord = allWords[randNum];
GameWords.Text = newWord;
}
Upvotes: 1
Reputation: 3009
There is a simple and optimized code for extract random text from a file.
public string GetRandomText()
{
Random r = new Random();
int _maxLine = 1000;
return File.ReadLines("C:\\txtWords.txt").Skip(r.Next(1, _maxLine)).Take(1).First();
}
Upvotes: 1