概要
SelectManyメソッドは、シーケンスに含まれる各要素について別のシーケンスを返し、これらのシーケンスを1つのシーケンスにフラット化します。この記事では、SelectManyメソッドの使用例について説明します。
公式サイト情報はコチラを参照してください。
構文
SelectManyメソッドは、以下のような構文を持ちます。
public static IEnumerable SelectMany<TSource, TResult>( this IEnumerable source, Func<TSource, IEnumerable> selector );
使用例
以下の例では、複数の文のリストがあり、それぞれの文を単語に分割してフラット化します。
List sentences = new List() { "This is the first sentence", "This is the second sentence", "This is the third sentence" }; IEnumerable words = sentences.SelectMany(s => s.Split(' ')); foreach (string word in words) { Console.WriteLine(word); }
実行結果は以下の通りです。
This is the first sentence This is the second sentence This is the third sentence
上記の例では、sentencesリストの各要素を文字列として取得し、Splitメソッドを使用してそれらを単語に分割します。SelectManyメソッドは、それぞれの要素に対して取得された単語のシーケンスを結合し、1つのフラット化されたシーケンスを返します。
.NET クラス Tips 一覧
これまでに紹介した .NET Tips 一覧はこちら。
Please follow and like us:
コメント