Caution
お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。
Enumerable.Select()
シーケンスの各要素を変換して新しいシーケンスを生成する LINQ の拡張メソッドです。ネストされたシーケンスを平坦化する『SelectMany()』も合わせて解説します。
構文
using System.Linq; // 各要素を変換して新しいシーケンスを返します。 IEnumerable<TResult> result = source.Select(x => 変換式); // ネストされたシーケンスを一段階平坦化します。 IEnumerable<TResult> flat = source.SelectMany(x => x.InnerCollection); // コレクション要素と親要素を組み合わせて変換します。 IEnumerable<TResult> flat2 = source.SelectMany(x => x.Items, (parent, child) => 変換式);
メソッド一覧
| メソッド | 概要 |
|---|---|
| Select(selector) | 各要素を変換して新しいシーケンスを返します。 |
| Select((x, i) => ...) | 要素とインデックスを使って変換します。 |
| SelectMany(collectionSelector) | ネストされたコレクションを一段階平坦化します。 |
| SelectMany(collectionSelector, resultSelector) | 平坦化しながら要素を変換します。 |
サンプルコード
using System;
using System.Collections.Generic;
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 各要素を 2 倍に変換します。
IEnumerable<int> doubled = numbers.Select(n => n * 2);
Console.WriteLine(string.Join(", ", doubled)); // 2, 4, 6, 8, 10
// 数値を文字列に変換します。
IEnumerable<string> strs = numbers.Select(n => $"No.{n}");
Console.WriteLine(string.Join(", ", strs)); // No.1, No.2, No.3, No.4, No.5
// インデックス付きで位置情報を含む文字列に変換します。
IEnumerable<string> indexed = numbers.Select((n, i) => $"[{i}]={n}");
Console.WriteLine(string.Join(", ", indexed)); // [0]=1, [1]=2, [2]=3, [3]=4, [4]=5
// 匿名型(anonymous type)に変換してオブジェクトを生成します。
var items = numbers.Select(n => new { Value = n, Square = n * n });
foreach (var item in items)
Console.WriteLine($"値:{item.Value}, 二乗:{item.Square}");
// SelectMany でネストされたリストを平坦化します。
List<List<int>> nested = new List<List<int>>
{
new List<int> { 1, 2 },
new List<int> { 3, 4 },
new List<int> { 5 },
};
IEnumerable<int> flat = nested.SelectMany(x => x);
Console.WriteLine(string.Join(", ", flat)); // 1, 2, 3, 4, 5
// 文字列リストの各文字を平坦化して取得します。
List<string> words = new List<string> { "abc", "de" };
IEnumerable<char> chars = words.SelectMany(w => w);
Console.WriteLine(string.Join(", ", chars)); // a, b, c, d, e
概要
『Select()』は他の言語の『map』に相当する操作で、各要素を一対一で変換します。戻り値の型を変えることもでき、匿名型を使うと複数のプロパティを持つオブジェクトに変換できます。
『SelectMany()』は多対一(ファンアウト)の変換で、各要素が持つコレクションを取り出して一つの平坦なシーケンスにまとめます。『Select()』でネストされたコレクションを変換すると結果が二重になるため、平坦化が必要な場合は『SelectMany()』を使ってください。
条件に合う要素だけを変換したい場合は『Enumerable.Where()』と組み合わせてください。変換結果を並べ替えたい場合は『Enumerable.OrderBy()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。