LoginSignup
7
7

More than 5 years have passed since last update.

Re: LINQでIE<T>からランダムに要素を取り出す

Last updated at Posted at 2014-03-26

LINQでIEからランダムに要素を取り出す を見ていて、IEnumerableを2回パスするのは嫌だなあと感じたので、ワンパスバージョンを作成しました。

using System;
using System.Collections.Generic;

public static class EnumeratorEx {
  private static readonly Random rand = new Random();

  public static T Random<T>(this IEnumerable<T> arg) {
    T selected = default(T);
    var n = 0;
    foreach (var item in arg) {
      n += 1;
      if (rand.Next(n) == 0) {
        selected = item;
      }
    }
    return selected;
  }
}

public class Test {
  public static void Main() {
    var items = new[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    for (int i = 0; i < 100; i++) {
      Console.Write(items.Random() + ", ");
    }
  }
}

1~0まで全部表示されるので、大丈夫そうです。
あと、パフォーマンスは計測していません。

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