Linq-projection-operations

提供:Dev Guides
移動先:案内検索

LINQの投影操作

投影とは、オブジェクトを特定のプロパティのみを持つまったく新しいフォームに変換する操作です。

Operator Description C# Query Expression Syntax VB Query Expression Syntax
Select The operator projects values on basis of a transform function select Select
SelectMany The operator project the sequences of values which are based on a transform function as well as flattens them into a single sequence Use multiple from clauses Use multiple From clauses

選択の例-クエリ式

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {

         List<string> words = new List<string>() { "an", "apple", "a", "day" };

         var query = from word in words select word.Substring(0, 1);

         foreach (string s in query)
            Console.WriteLine(s);
            Console.ReadLine();
      }
   }
}

VB

Module Module1

   Sub Main()

      Dim words = New List(Of String) From {"an", "apple", "a", "day"}

      Dim query = From word In words Select word.Substring(0, 1);

      Dim sb As New System.Text.StringBuilder()

      For Each letter As String In query
         sb.AppendLine(letter)
         Console.WriteLine(letter)
      Next
         Console.ReadLine()

   End Sub

End Module

C#またはVBの上記のコードがコンパイルされて実行されると、次の結果が生成されます-

a
a
a
d

SelectManyの例-クエリ式

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {

         List<string> phrases = new List<string>() { "an apple a day", "the quick brown fox" };

         var query = from phrase in phrases
                     from word in phrase.Split(' ')
                     select word;

         foreach (string s in query)
            Console.WriteLine(s);
            Console.ReadLine();
      }
   }
}

VB

Module Module1

   Sub Main()

      Dim phrases = New List(Of String) From {"an apple a day", "the quick brown fox"}

      Dim query = From phrase In phrases
                  From word In phrase.Split(" "c)
                  Select word;

      Dim sb As New System.Text.StringBuilder()

      For Each str As String In query
         sb.AppendLine(str)
         Console.WriteLine(str)
      Next
         Console.ReadLine()

   End Sub

End Module

C#またはVBの上記のコードがコンパイルされて実行されると、次の結果が生成されます-

an
apple
a
day
the
quick
brown
fox