LINQ投影操作


投影是在其中一個物件被變換成僅特定效能一種全新的形式的操作。

運算子 描述 C#查詢表示式語法 VB查詢表示式語法
Select 操作轉換函式的基礎專案值 select Select
SelectMany 操作專案的值是根據上的轉換函式,以及拼合成一個單一的序列的序列 使用多個from子句 使用多個from子句

Select的例子- 查詢表示式

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