Consider I have a file "new.txt" like,
asdfg
qwerty
zcx
poi
Now i need to shuffle the lines of this text file. How can i do this in C#.?
Consider I have a file "new.txt" like,
asdfg
qwerty
zcx
poi
Now i need to shuffle the lines of this text file. How can i do this in C#.?
a not really performant way would be: read the file into a IEnumerable<string>
, make a .OrderBy(line => Guid.NewGuid())
and write that in the file
eg.
var originalLines = File.ReadAllLines("test.txt");
var shuffledLines = lines.OrderBy(line => Guid.NewGuid()).ToArray();
File.WriteAllLines("test.txt", shuffledLines);
you can put each line in an array and rewrite your file with a random index of the array
My first guess would be to load all lines in a
List<string>
Then shuffle the list, and write it back in the file, but this my be a bit heavy if the file is big...
var lines = File.ReadAllLines("test.txt");
var rnd = new Random();
lines = lines.OrderBy(line => rnd.Next()).ToArray();
File.WriteAllLines("test.txt", lines);
I found doing this in MS Excel helpful and thought of posting it here.
1) Copy the contents of the file to Columns in MS Excel.
2) Then in the next column first cell (say B1) type the formula =rand().
3) Select the column B, by clicked on the title
4) Edit->Fill->Down fills all the cells with random values
5) Select the contents to be sorted and this column B and sort Ascending.
thus the contents will be shuffled which can be copied and pasted in text document.