开发者

Shuffle lines in a file in .NET

Consider I have a file "new.txt" like,

asdfg
qwerty
zcx
poi

Now i need 开发者_StackOverflow中文版to shuffle the lines of this text file. How can i do this in C#.?


var lines = File.ReadAllLines("test.txt");
var rnd = new Random();
lines = lines.OrderBy(line => rnd.Next()).ToArray();
File.WriteAllLines("test.txt", lines);


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);


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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜