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

Example of SelectMany - Query Expression

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

linq_query_operators.html