Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

アイデアは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

kuchikios
✌('ω')✌
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away