R.Tanaka.Ichiro's Blog

主にC# な話題です

目次

Blog 利用状況

ニュース

SelectMany

先日知った話ですが、忘れないようにメモ。
というか、いきなりコードと実行結果。


Console.WriteLine("---------/ q1 /------------");
var q1 =
  from y in Enumerable.Range(1, 3)
  from x in Enumerable.Range(1, 3)
  select String.Format("y = {0} : x = {1}", y, x);
foreach(var i in q1) Console.WriteLine(i);

Console.WriteLine("---------/ q2 /------------");
var q2 =
  Enumerable.Range(1, 3).Select(y =>
  Enumerable.Range(1, 3).Select(x => String.Format("y = {0} : x = {1}", y, x)));
foreach(var i in q2) Console.WriteLine(i);

Console.WriteLine("---------/ q3 /------------");
var q3 =
  Enumerable.Range(1, 3).SelectMany(y =>
  Enumerable.Range(1, 3).Select(x => String.Format("y = {0} : x = {1}", y, x)));
foreach(var i in q3) Console.WriteLine(i);

---------/ q1 /------------
y = 1 : x = 1
y = 1 : x = 2
y = 1 : x = 3
y = 2 : x = 1
y = 2 : x = 2
y = 2 : x = 3
y = 3 : x = 1
y = 3 : x = 2
y = 3 : x = 3
---------/ q2 /------------
System.Linq.Enumerable+<SelectIterator>d__d`2[System.Int32,System.String]
System.Linq.Enumerable+<SelectIterator>d__d`2[System.Int32,System.String]
System.Linq.Enumerable+<SelectIterator>d__d`2[System.Int32,System.String]
---------/ q3 /------------
y = 1 : x = 1
y = 1 : x = 2
y = 1 : x = 3
y = 2 : x = 1
y = 2 : x = 2
y = 2 : x = 3
y = 3 : x = 1
y = 3 : x = 2
y = 3 : x = 3


考えてみれば

そりゃそうだよなー

な結果です。

from が 2 つ以上重なるクエリー式をメソッドに書き直す時は、SelectMany を使う点に注意です。

投稿日時 : 2008年2月6日 13:57

Feedback

# [.NET]図解 SelectMany 2008/02/06 15:14 NyaRuRuの日記

元ネタ『SelectMany - R.Tanaka.Ichiro’s Blog』 LINQ のオペレータは絵で描いてみると分かりやすいことがありますね. 私が持っている SelectMany のイメージ. ただ,この絵だと肝心のポイントがきちんと表現できていなくて,本当は入力列も出力列も無限に続く感を出した

# クエリー式とイテレータ 2008/02/12 10:28 R.Tanaka.Ichiro's Blog

クエリー式とイテレータ

# クエリー式とイテレータ 2008/02/12 10:30 R.Tanaka.Ichiro's Blog

クエリー式とイテレータ

# LepXEPwixdbuFmn 2011/12/16 2:29 http://www.healthinter.org/health/page/fosamax.php

Post brought me to think, went to mull over!!...

# weoDimTNOwbZ 2012/01/07 13:22 http://www.luckyvitamin.com/p-110235-dynamic-healt

Of course, I understand a little about this post but will try cope with it!!...

タイトル  
名前  
Url
コメント