One way to do it would be to filter the lines as you read them in from the file. We can do this by treating each line as a character array, excluding acceptable non-alpha-numeric characters by passing them as an IEnumerable
to the Linq
extension method .Except()
, and then we can test that .All
of the remaining characters are alphabetic by calling the IsLetter
method of the char
struct (which returns true if the character is a letter).
For example:
Random random = new Random();
static void Main()
{
// Valid non-alphanumeric characters are stored in this list.
// Currently this is only a space, but you can add other valid
// punctuation here (periods, commas, etc.) if necessary.
var validNonAlphaChars = new List<char> {' '};
// Get all lines that contain only letters (after
// excluding the valid non-alpha characters).
var fileLines = File.ReadAllLines(@"c:\temp\temp.txt")
.Where(line => line.Except(validNonAlphaChars).All(char.IsLetter))
.ToList();
// Shuffle the lines so they're in a random order using the Fisher-Yates
// algorithm (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
for (int i = 0; i < fileLines.Count; i++)
{
// Select a random index after i
var rndIndex = i + random.Next(fileLines.Count - i);
// Swap the item at that index with the item at i
var temp = fileLines[rndIndex];
fileLines[rndIndex] = fileLines[i];
fileLines[i] = temp;
}
// Now we can output the lines sequentially from fileLines
// and the order will be random (and non-repeating)
fileLines.ForEach(Console.WriteLine);
GetKeyFromUser("\nPress any key to exit...");
}