7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LINQメソッドにShuffleを追加する

Last updated at Posted at 2013-03-01

アイデアはDOBON.NET(Coding Horror)から。

public static IOrderedEnumerable<TSource> Shuffle<TSource>(
	this IEnumerable<TSource> source )
{
	return source.OrderBy( x => Guid.NewGuid( ) );
}

使用例:

var values = new[ ] { 1, 2, 3, 4, 5 };
foreach ( var value in values.Shuffle( ) )
{
	Console.WriteLine( value );
}

Console.WriteLine( "終了するには何かキーを押して下さい..." );
Console.ReadKey( );

実行結果

2
5
3
4
1
終了するには何かキーを押して下さい...

DOBON.NET: http://dobon.net/vb/dotnet/programing/arrayshuffle.html
Coding Horror: http://www.codinghorror.com/blog/2007/12/shuffling.html

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?