LoginSignup
6
7

More than 5 years have passed since last update.

C#のLINQで扱う無限リスト

Last updated at Posted at 2016-04-01

今日は μ’s final LoveLiveの最終日です

C#で無限リストを扱いたい時の例です。

using System;
using System.Collections.Generic;
using System.Linq;

static class MuseSaying {
    public static IEnumerable<IEnumerable<string>> SayInfinite() {
      var words = new [] {
            "ファイトだよ!"
          , "ラブアローシュートッ!!"
          , "ヨキニハカラエミナノシュー!"
          , "ダレカタスケテー!!"
          , "にゃー!!"
          , "イミワカンナイ!!"
          , "にっこにっこにー!"
          , "ぷしゅっ!"
          , "ハラショー"
      }
      .Select(x => string.Format(@"\{0}/", x));
      while(true) {
        yield return words;
      }
    }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> xs) {
        return xs.OrderBy(_ => Guid.NewGuid());
    }
}

class Muse {
    public static void Main(string[] args) {
        MuseSaying.SayInfinite()
            .Select(xs => xs.Shuffle())
            .Take(100)
            .ToList().ForEach(xs => xs.ToList().ForEach(Console.WriteLine));
    }
}

ShuffleメソッドはIEnumerableをシャッフルするShuffleメソッドです。

LazyでInfinityなListなのですが、Take()しないと無限に評価されてしまうので

Take()やTakeWhile()で打ち止めて上げてください。

μ’sの皆さん、今日という日をおめでとうございます!! そしてありがとうございます!!
μ’sのみんなからもらった大切なものを大切にしていきます…!

以上がC#のLINQで無限リストを扱う話でした。


参考URL

ラブライブ!μ's Final LoveLive!〜μ’sic Forever♪♪♪♪♪♪♪♪♪〜
LINQメソッドにShuffleを追加する
MSDN System.Linq.Enumerable
C#でフィボナッチ数列を求める

6
7
2

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