「LINQ - 拡張メソッド一覧」の版間の差分

ナビゲーションに移動 検索に移動
編集の要約なし
編集の要約なし
230行目: 230行目:
  //    Key=16, Source={{ Name = Java, Age = 16 }},
  //    Key=16, Source={{ Name = Java, Age = 16 }},
  //    Key=8, Source={{ Name = Groovy, Age = 8 }, { Name = Scala, Age = 8 }}}
  //    Key=8, Source={{ Name = Groovy, Age = 8 }, { Name = Scala, Age = 8 }}}
</source>
<br><br>
== 結合 ==
<center>
{| class="wikitable"
|-
! メソッド名 !! 機能
|-
| Join || 内部結合を行ったシーケンスを返す。
|-
| GroupJoin || 左外部結合を行って指定のキーでグループ化する。その "キーとグループ" のシーケンスを返す。
|-
| Concat || 2つのシーケンスを連結する。(Unionは同じ要素を一つにまとめるが、Concatは元の要素をすべて返す)
|-
| DefaultIfEmpty || シーケンスを返す。シーケンスが空なら、規定値もしくは任意の要素を返す。
|-
| Zip || 指定した関数で、2つのシーケンスを1つのシーケンスにマージする。
|}
</center>
<source lang="c#">
var outer = new[] {
    new{Name = "C#", Age = 11},
    new{Name = "Java", Age = 16},
    new{Name = "Groovy", Age = 8},
    new{Name = "Scala", Age = 8},
};
var outer2 = new[] {
    new{Name = "Python", Age = 21},
    new{Name = "COBOL", Age = 52},
};
var inner = new[] {
    new{Name = "C#", DesignedBy = "Microsoft"},
    new{Name = "Java", DesignedBy = "Sun Microsystems"},
    new{Name = "Java", DesignedBy = "Oracle"},
};
Console.WriteLine(outer.Join(inner, o => o.Name, i => i.Name, (o, i) => new { o.Name, o.Age, i.DesignedBy}).ToResult());
// → {{ Name = C#, Age = 11, DesignedBy = Microsoft },
//    { Name = Java, Age = 16, DesignedBy = Sun Microsystems },
//    { Name = Java, Age = 16, DesignedBy = Oracle }}
Console.WriteLine(outer.GroupJoin(inner, o => o.Name, i => i.Name, (o, i) =>
                                  new { o.Name, o.Age, DesigndBy = i.Select(e => e.DesignedBy).ToResult() }).ToResult());
// → {{ Name = C#, Age = 11, DesigndBy = {Microsoft} },
//    { Name = Java, Age = 16, DesigndBy = {Sun Microsystems, Oracle} },
//    { Name = Groovy, Age = 8, DesigndBy = {} },
//    { Name = Scala, Age = 8, DesigndBy = {} }}
Console.WriteLine(outer.Concat(outer2).ToResult());
// → {{ Name = C#, Age = 11 },
//    { Name = Java, Age = 16 },
//    { Name = Groovy, Age = 8 },
//    { Name = Scala, Age = 8 },
//    { Name = Python, Age = 21 },
//    { Name = COBOL, Age = 52 }}
Console.WriteLine(outer.DefaultIfEmpty().ToResult());
// → {{ Name = C#, Age = 11 },
//    { Name = Java, Age = 16 },
//    { Name = Groovy, Age = 8 },
//    { Name = Scala, Age = 8 }}
Console.WriteLine(outer.Zip(outer2, (o1, o2) => o1.Name + "&" + o2.Name).ToResult());
// → {C#&Python, Java&COBOL}
  </source>
  </source>
<br><br>
<br><br>
匿名利用者

案内メニュー