tags:

views:

208

answers:

6

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#.?

+4  A: 

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);
Andreas Niedermair
A: 

you can put each line in an array and rewrite your file with a random index of the array

dada686
+3  A: 

A Fisher-Yates shuffle isn't that hard to implement, I think.

Joey
A: 

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...

Shimrod
+4  A: 
var lines = File.ReadAllLines("test.txt");
var rnd = new Random();
lines = lines.OrderBy(line => rnd.Next()).ToArray();
File.WriteAllLines("test.txt", lines);
Darin Dimitrov
+1  A: 

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.

pragadheesh
This really isn't in the scope of your own question, is it? Personally, I think Darin Dimitrov provided a good solution (it's what I would have suggested).
Anthony Pegram