15
10

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を使って、指定個数ランダムで取り出すには

Last updated at Posted at 2012-05-16

配列からランダムに指定個数選択するには、

  • .OrderBy()にGUIDを与えてランダムソートし、
  • .Take() で指定個数取得すれば良い
RandomTake.cs
using System;
using System.Collections.Generic;
using System.Linq;

IEnumerable<string> lines = new string[] {"1","2","3","4","5","6","7","8","9","10"};
IEnumerable<string> newLines;

newLines = lines.OrderBy(i => Guid.NewGuid()).Take(3);

foreach(var line in newLines)
{
  Console.WriteLine(line);
}
15
10
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
15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?