LINQ - 查询运算符

LINQ - 查询运算符 首页 / LinQ入门教程 / LINQ - 查询运算符

形成查询模式的一组扩展方法称为LINQ标准查询运算符,作为LINQ查询表达式的构建块,这些运算符提供了一系列查询功能,如filtering,sorting,projection,aggregation等。

Filtering Operators

操作符说明 C#查询表达式语法 VB查询表达式语法
where基于predicate函数过滤值whereWhere
OfType根据指定类型的能力来过滤值不适用不适用

C#

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

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

         string[] words = { "humpty", "dumpty","set", "on", "a", "wall" };

         IEnumerable<string> query = from word in words where word.Length == 3 select word;
		 
         foreach (string str in query)
            Console.WriteLine(str);
            Console.ReadLine();            
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
      Dim words As String() = {"humpty", "dumpty", "set", "on", "a", "wall"}

      Dim query = From word In words Where word.Length = 3 Select word

      For Each n In query
         Console.WriteLine(n)
		 
      Next
         Console.ReadLine()
   End Sub
   
End Module

编译并执行以上C#或VB中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

set

Join Operators

操作符说明 C#查询表达式语法 VB查询表达式语法
Join根据匹配键将两个序列连接起来join…in…on…equalsFrom x In ...,y In ... Where x.a=y.a
GroupJoin加入两个序列并将匹配的元素分组join...in...on...equals...into...Group Join ... In ... On

C#

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

namespace Operators {
   class JoinTables {
      class DepartmentClass {
         public int DepartmentId { get; set; }
         public string Name { get; set; }
      }

      class EmployeeClass {
         public int EmployeeId { get; set; }
         public string EmployeeName { get; set; }
         public int DepartmentId { get; set; }
      }

      static void Main(string[] args) {
      
         List <DepartmentClass> departments = new List <DepartmentClass>();
         departments.Add(new DepartmentClass { DepartmentId = 1, Name = "Account" });
         departments.Add(new DepartmentClass { DepartmentId = 2, Name = "Sales" });
         departments.Add(new DepartmentClass { DepartmentId = 3, Name = "Marketing" });
       
         List <EmployeeClass> employees = new List <EmployeeClass>();
         employees.Add(new EmployeeClass { DepartmentId = 1, EmployeeId = 1, EmployeeName = "William" });
         employees.Add(new EmployeeClass { DepartmentId = 2, EmployeeId = 2, EmployeeName = "Miley" });
         employees.Add(new EmployeeClass { DepartmentId = 1, EmployeeId = 3, EmployeeName = "Benjamin" });


         var list = (from e in employees join d in departments on e.DepartmentId equals d.DepartmentId select new {
            EmployeeName = e.EmployeeName,
            DepartmentName = d.Name
         });
            
         foreach (var e in list) {
            Console.WriteLine("Employee Name={0} , Department Name={1}", e.EmployeeName, e.DepartmentName);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey(); 
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim account As New Department With {.Name = "Account", .DepartmentId = 1}
      Dim sales As New Department With {.Name = "Sales", .DepartmentId = 2}
      Dim marketing As New Department With {.Name = "Marketing", .DepartmentId = 3}

      Dim departments As New System.Collections.Generic.List(Of Department)(New Department() {account, sales, marketing})

      Dim william As New Employee With {.EmployeeName = "William", .EmployeeId = 1, .DepartmentId = 1}
      Dim miley As New Employee With {.EmployeeName = "Miley", .EmployeeId = 2, .DepartmentId = 2}
      Dim benjamin As New Employee With {.EmployeeName = "Benjamin", .EmployeeId = 3, .DepartmentId = 1}

      Dim employees As New System.Collections.Generic.List(Of Employee)(New Employee() {william, miley, benjamin})

      Dim list = (From e In employees
                  Join d In departments On e.DepartmentId Equals d.DepartmentId
                  Select New Person With {.EmployeeName = e.EmployeeName, .DepartmentName = d.Name})

      For Each e In list
         Console.WriteLine("Employee Name={0} , Department Name={1}", e.EmployeeName, e.DepartmentName)
      Next

      Console.WriteLine(vbLf &"Press any key to continue.")
      Console.ReadKey()
   End Sub

   Class Employee
      Public Property EmployeeId As Integer
      Public Property EmployeeName As String
      Public Property DepartmentId As Integer
   End Class

   Class Department
      Public Property Name As String
      Public Property DepartmentId As Integer
   End Class

   Class Person
      Public Property EmployeeName As String
      Public Property DepartmentName As String
   End Class
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

Emplyee Name=William, Department Name=Account
Emplyee Name=Miley, Department Name=Sales
Emplyee Name=Benjamin, Department Name=Account

Press any key to continue.

Projection Operations

操作符说明 C#查询表达式语法 VB查询表达式语法
Select根据转换函数值selectSelect
SelectMany运算符投影基于变换函数的值序列,并将其展平为单个序列Use multiple from clausesUse multiple From clauses

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中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

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中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

an
apple
a
day
the
quick
brown
fox

Sorting Operators

操作符说明 C#查询表达式语法 VB查询表达式语法
OrderBy按升序对值进行排序 orderbyOrder By
OrderByDescending按降序对值进行排序 orderby ...descendingOrder By ... Descending
ThenBy以升序执行二级排序 orderby…,…Order By...,...
ThenByDescending以降序执行辅助排序 orderby…,…descendingOrder By ...,...Descending
Reverse反转集合中元素的顺序不适用不适用

OrderBy,OrderByDescending的示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         int[] num = { -20, 12, 6, 10, 0, -3, 1 };
			
         //create a query that obtain the values in sorted order
         var posNums = from n in num
                       orderby n
                       select n;
							  
         Console.Write("Values in ascending order: ");
     
         //Execute the query and display the results.
		 
         foreach (int i in posNums) 
            Console.Write(i + "\n");

            var posNumsDesc = from n in num
                              orderby n descending
                              select n;
										
            Console.Write("\nValues in descending order: ");

         //Execute the query and display the results.
		 
         foreach (int i in posNumsDesc) 
            Console.Write(i + "\n");

            Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1};

      Dim posNums = From n In num
                    Order By n
                    Select n;
						  
      Console.Write("Values in ascending order: ");

      For Each n In posNums
         Console.WriteLine(n)
      Next
 
      Dim posNumsDesc = From n In num
                       Order By n Descending
                       Select n;
							  
         Console.Write("Values in descending order: ");

      For Each n In posNumsDesc
         Console.WriteLine(n)
		
      Next
         Console.ReadLine()
		
   End Sub
  
End Module

编译并执行以上C#或VB中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

Values in ascending order: -20 
-3 
0 
1 
6 
10 
12
Values in descending order: 12 
10 
6 
1 
0 
-3 
-20

Grouping Operators

运算符基于共同的共享属性将数据分为几组。

操作符描述C# Query Expression SyntaxVB Query Expression Syntax
GroupBy将它们作为IGrouping <key,element>类型的IEnumerable集合返回group … by -or- group … by … into …Group … By … Into …
ToLookup执行分组操作,其中返回键对序列不适用不适用

GroupBy的示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 };

         IEnumerable<IGrouping<int, int>> query = from number in numbers 
		                              group number by number % 2;    

         foreach (var group in query) {
            Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:");
           
            foreach (int i in group)
               Console.WriteLine(i);
         }
			
         Console.ReadLine();                
      }
   }
}

VB

无涯教程网

Module Module1
   Sub Main()
      Dim numbers As New System.Collections.Generic.List(Of Integer)(
      New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208})

      Dim query = From number In numbers 
                  Group By Remainder = (number Mod 2) Into Group
     
      For Each group In query
         Console.WriteLine(If(group.Remainder = 0, vbCrLf &"Even numbers:", vbCrLf &"Odd numbers:"))
		 
         For Each num In group.Group           
            Console.WriteLine(num)
         Next 
		 
      Next
	  
      Console.ReadLine()
	  
   End Sub
   
End Module

编译并执行以上C#或VB中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

Odd numbers: 
35 
3987 
199 
329 

Even numbers: 
44 
200 
84 
4 
446 
208

Conversions

Operator描述C# Query Expression SyntaxVB Query Expression Syntax
AsEnumerable返回输入类型为IEnumerable <T>的输入不适用不适用
AsQueryable(generic) IEnumerable转换为(generic)IQueryable不适用不适用
Cast将集合的元素强制转换为指定的类型from string str in wordsFrom … As …
OfType根据其值过滤值,具体取决于将其强制转换为特定类型的能力不适用不适用
ToArray强制执行查询并将集合转换为数组不适用不适用
ToDictionary根据键选择器功能,将元素设置为Dictionary <TKey,TValue>并强制执行LINQ查询不适用不适用
ToList通过将集合转换为List <T>来强制执行查询 不适用不适用
ToLookup强制执行查询,并根据键选择器函数将元素放入Lookup <TKey,TElement>不适用不适用

Cast 转换查询示例

C#

using System;
using System.Linq;

namespace Operators {
   class Cast {
      static void Main(string[] args) {
      
         Plant[] plants = new Plant[] {new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" },
                          new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" },
                          new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" },
                          new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }};

         var query = from CarnivorousPlant cPlant in plants
                     where cPlant.TrapType == "Snap Trap"
                     select cPlant;

         foreach (var e in query) {
            Console.WriteLine("Name={0} , Trap Type={1}", e.Name, e.TrapType);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }

   class Plant {
      public string Name { get; set; }
   }

   class CarnivorousPlant : Plant {
      public string TrapType { get; set; }
   }
}

VB

无涯教程网

Module Module1
   Sub Main()

      Dim plants() As Plant = {New CarnivorousPlant With {.Name = "Venus Fly Trap", .TrapType = "Snap Trap"},
                              New CarnivorousPlant With {.Name = "Pitcher Plant", .TrapType = "Pitfall Trap"},
                              New CarnivorousPlant With {.Name = "Sundew", .TrapType = "Flypaper Trap"},
                              New CarnivorousPlant With {.Name = "Waterwheel Plant", .TrapType = "Snap Trap"}}

      Dim list = From cPlant As CarnivorousPlant In plants
                 Where cPlant.TrapType = "Snap Trap"
                 Select cPlant

      For Each e In list
         Console.WriteLine("Name={0} , Trap Type={1}", e.Name, e.TrapType)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
   End Sub

   Class Plant
      Public Property Name As String
   End Class

   Class CarnivorousPlant
      Inherits Plant
      Public Property TrapType As String
   End Class

End Module

编译并执行以上C#或VB中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

Name=Venus Fly Trap, TrapType=Snap Trap
Name=Waterwheel Plant, TrapType=Snap Trap

Press any key to continue.

Concatenation

执行两个序列的串联操作,就其操作而言,它与Union运算符非常相似,不同之处在于它不会删除重复项。

操作符说明 C#查询表达式语法 VB查询表达式语法
Concat串联两个序列以形成单个序列。不适用不适用

Concat的示例  - Enumerable.Concat(Of TSource)方法

C#

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

namespace Operators {
   class Concat {
      static void Main(string[] args) {
      
         Pet[] cats=GetCats();
         Pet[] dogs=GetDogs();

         IEnumerable<string> query=cats.Select(cat  cat.Name).Concat(dogs.Select(dog => dog.Name));

         foreach (var e in query) {
            Console.WriteLine("Name={0} ", e);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }

      static Pet[] GetCats() {
         Pet[] cats={ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };
         return cats;
      }

      static Pet[] GetDogs() {
         Pet[] dogs={ new Pet { Name="Bounder", Age=3 },
                       new Pet { Name="Snoopy", Age=14 },
                       new Pet { Name="Fido", Age=9 } };
					   
         return dogs;
      }
   }

   class Pet {
      public string Name { get; set; }
      public int Age { get; set; }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()

      Dim cats As List(Of Pet)=GetCats()
      Dim dogs As List(Of Pet)=GetDogs()

      Dim list=cats.Cast(Of Pet)().Concat(dogs.Cast(Of Pet)()).ToList()

      For Each e In list
         Console.WriteLine("Name={0}", e.Name)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub

   Function GetCats() As List(Of Pet)

      Dim cats As New List(Of Pet)

         cats.Add(New Pet With {.Name="Barley", .Age=8})
         cats.Add(New Pet With {.Name="Boots", .Age=4})
         cats.Add(New Pet With {.Name="Whiskers", .Age=1})

      Return cats
	  
   End Function

   Function GetDogs() As List(Of Pet)

      Dim dogs As New List(Of Pet)

         dogs.Add(New Pet With {.Name="Bounder", .Age=3})
         dogs.Add(New Pet With {.Name="Snoopy", .Age=14})
         dogs.Add(New Pet With {.Name="Fido", .Age=9})

      Return dogs
	  
   End Function

   Class Pet
      Public Property Name As String
      Public Property Age As Integer
   End Class
   
End Module

编译并执行以上C#或VB中的代码时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-query-operators.html

来源:LearnFk无涯教程网

Barley 
Boots 
Whiskers 
Bounder 
Snoopy 
Fido

Press any key to continue.

Aggregation

执行任何类型的所需聚合,并允许在LINQ中创建自定义聚合。

操作符说明 C#查询表达式语法 VB查询表达式语法
Aggregate对集合的值进行操作以执行自定义聚合操作不适用不适用
Average计算值集合的平均值不适用Aggregate ... In ... Into Average()
Count计算集合中满足断言功能的元素不适用Aggregate ... In ... Into Count()
LonCount计算巨大集合中满足断言功能的元素不适用Aggregate…In… Into LongCount()
Max找出集合中的最大值不适用Aggregate…In…Into Max()
Min找出集合中存在的最小值不适用Aggregate…In…Into Min()
Sum找出集合中值的总和不适用Aggregate…In…Into Sum()

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

      Dim intDivByTwo = Aggregate n In num
                       Where n > 6
                       Into Count()
      Console.WriteLine("Count of Numbers: " & intDivByTwo)

      Dim intResult = Aggregate n In num
                     Where n > 6
                     Into Average()
							
      Console.WriteLine("Average of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Where n > 6
                 Into LongCount()
					  
      Console.WriteLine("Long Count of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Max()
					  
      Console.WriteLine("Max of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Min()
					  
      Console.WriteLine("Min of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Sum()
					  
      Console.WriteLine("Sum of Numbers: " & intResult)

      Console.ReadLine()

   End Sub
   
End Module

编译并执行上述VB代码后,将产生以下输出-

Count of Numbers: 3
Average of Numbers: 8
Long Count of Numbers: 3
Max of Numbers: 9
Min of Numbers: 1
Sum of Numbers: 45

Quantifier Operations

当序列中的某些或所有元素满足特定条件时,这些运算符将返回布尔值,即True或False。

Operator说明 C#查询表达式语法 VB查询表达式语法
All如果序列中的所有元素都满足断言条件,则返回值" True"不适用Aggregate…In…Into All(…)
Any通过搜索一个序列来确定同一元素是否满足指定条件不适用Aggregate…In…Into Any()
Contains如果发现序列中不存在特定元素,则返回"True"值,如果序列中不包含该特定元素,则返回"False"值不适用不适用

All(Of TSource) 方法的示例

VB

无涯教程网

Module Module1

   Sub Main()

      Dim barley As New Pet With {.Name = "Barley", .Age = 4}
      Dim boots As New Pet With {.Name = "Boots", .Age = 1}
      Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}
      Dim bluemoon As New Pet With {.Name = "Blue Moon", .Age = 9}
      Dim daisy As New Pet With {.Name = "Daisy", .Age = 3}

      Dim charlotte As New Person With {.Name = "Charlotte", .Pets = New Pet() {barley, boots}}
      Dim arlene As New Person With {.Name = "Arlene", .Pets = New Pet() {whiskers}}
      Dim rui As New Person With {.Name = "Rui", .Pets = New Pet() {bluemoon, daisy}}

      Dim people As New System.Collections.Generic.List(Of Person)(New Person() {charlotte, arlene, rui})

      Dim query = From pers In people
                  Where (Aggregate pt In pers.Pets Into All(pt.Age > 2))
                  Select pers.Name

      For Each e In query
         Console.WriteLine("Name={0}", e)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub

   Class Person
      Public Property Name As String
      Public Property Pets As Pet()
   End Class

   Class Pet
      Public Property Name As String
      Public Property Age As Integer
   End Class
   
End Module

在VB中将以上代码编译并执行广告后,会产生以下输出-

Arlene 
Rui 

Press any key to continue.

Any示例

VB

无涯教程网

Module Module1

   Sub Main()

      Dim barley As New Pet With {.Name = "Barley", .Age = 4}
      Dim boots As New Pet With {.Name = "Boots", .Age = 1}
      Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}
      Dim bluemoon As New Pet With {.Name = "Blue Moon", .Age = 9}
      Dim daisy As New Pet With {.Name = "Daisy", .Age = 3}

      Dim charlotte As New Person With {.Name = "Charlotte", .Pets = New Pet() {barley, boots}}
      Dim arlene As New Person With {.Name = "Arlene", .Pets = New Pet() {whiskers}}
      Dim rui As New Person With {.Name = "Rui", .Pets = New Pet() {bluemoon, daisy}}

      Dim people As New System.Collections.Generic.List(Of Person)(New Person() {charlotte, arlene, rui})

      Dim query = From pers In people
                  Where (Aggregate pt In pers.Pets Into Any(pt.Age > 7))
                  Select pers.Name

      For Each e In query
         Console.WriteLine("Name={0}", e)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub

   Class Person
      Public Property Name As String
      Public Property Pets As Pet()
   End Class

   Class Pet
      Public Property Name As String
      Public Property Age As Integer
   End Class
   
End Module

在VB中将以上代码编译并执行广告后,会产生以下输出-

Rui

Press any key to continue. 

Partition Operators

将输入序列分为两个单独的部分,而无需重新排列序列的元素,然后返回其中一个。

Operator说明 C#查询表达式语法 VB查询表达式语法
Skip跳过序列中指定数量的元素,然后返回其余元素不适用Skip
SkipWhile与"Skip"相同,唯一的不同是要通过布尔条件指定要跳过的元素数不适用Skip While
Take从序列中获取指定数量的元素,然后跳过其余元素不适用Take
TakeWhile与Take相同,不同之处在于要获取的元素数由布尔条件指定不适用Take While

Skip示例

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

      Dim query = From word In words
                  Skip 4

      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

当以上代码在VB中编译并执行时,将产生以下输出-

there
was
a
jungle

SkipWhile的示例

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

      Dim query = From word In words 
                  Skip While word.Substring(0, 1) = "t" 

      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

当以上代码在VB中编译并执行时,将产生以下输出-

once
upon
a
was
a
jungle

Take查询表达式示例

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

      Dim query = From word In words 
                  Take 3 

      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

当以上代码在VB中编译并执行时,将产生以下输出-

once
upon
a

Take While示例

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim words = {"once", "upon", "a", "time", "there", "was", "a", "jungle"}

      Dim query = From word In words 
                  Take While word.Length < 6 

      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

当以上代码在VB中编译并执行时,将产生以下输出-

once
upon
a
time
there
was
a

Generation Operations

代数运算符会创建一个新的值序列。

Operator说明 C#查询表达式语法 VB查询表达式语法
DefaultIfEmpty应用于空序列时,在序列中生成一个默认元素不适用不适用
Empty返回空值序列,是最简单的世代运算符不适用不适用
Range生成具有整数或数字序列的集合不适用不适用
Repeat生成包含特定长度重复值的序列不适用不适用

DefaultIfEmpty的示例

C#

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

namespace Operators {
   class DefaultEmpty {
      static void Main(string[] args) {
      
         Pet barley = new Pet() { Name = "Barley", Age = 4 };
         Pet boots = new Pet() { Name = "Boots", Age = 1 };
         Pet whiskers = new Pet() { Name = "Whiskers", Age = 6 };
         Pet bluemoon = new Pet() { Name = "Blue Moon", Age = 9 };
         Pet daisy = new Pet() { Name = "Daisy", Age = 3 };

         List<Pet> pets = new List<Pet>() { barley, boots, whiskers, bluemoon, daisy };

         foreach (var e in pets.DefaultIfEmpty()) {
            Console.WriteLine("Name={0} ", e.Name);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }

      class Pet {
         public string Name { get; set; }
         public int Age { get; set; }
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()

      Dim barley As New Pet With {.Name = "Barley", .Age = 4}
      Dim boots As New Pet With {.Name = "Boots", .Age = 1}
      Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}
      Dim bluemoon As New Pet With {.Name = "Blue Moon", .Age = 9}
      Dim daisy As New Pet With {.Name = "Daisy", .Age = 3}

      Dim pets As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots, whiskers, bluemoon, daisy})

      For Each e In pets.DefaultIfEmpty()
         Console.WriteLine("Name={0}", e.Name)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
   End Sub

   Class Pet
      Public Property Name As String
      Public Property Age As Integer
   End Class
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

Name=Barley 
Name=Boots 
Name=Whiskers
Name=Blue Moon
Name=Daisy

Press any key to continue.

Range示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
         //Generate a sequence of integers from 1 to 5  
         //and then select their squares.
		 
         IEnumerable<int> squares = Enumerable.Range(1, 5).Select(x => x * x);

         foreach (int num in squares) {
            Console.WriteLine(num);
         }
			
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim squares As IEnumerable(Of Integer) = _Enumerable.Range(1, 5).Select(Function(x) x * x)

      Dim output As New System.Text.StringBuilder
	  
      For Each num As Integer In squares
         output.AppendLine(num)
         Console.WriteLine(num)
      Next
		
      Console.ReadLine()
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

1
4
9
16
25

Repeat的示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
         IEnumerable<string> strings = Enumerable.Repeat("I like programming.", 3);

         foreach (String str in strings) {
            Console.WriteLine(str);
         }
			
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim sentences As IEnumerable(Of String) = _Enumerable.Repeat("I like programming.", 3)

      Dim output As New System.Text.StringBuilder
	  
      For Each sentence As String In sentences
         output.AppendLine(sentence)
         Console.WriteLine(sentence)
      Next

      Console.ReadLine()
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

I like programming.
I like programming.
I like programming.

Set Operations

设置操作有四个运算符,每个运算符根据不同的标准得出输出。

Operator说明 C#查询表达式语法 VB查询表达式语法
Distinct通过过滤重复数据(如果有的话)从集合中获得唯一值列表不适用Distinct
Except比较两个集合的值,并从一个集合中返回不在另一个集合中的值不适用不适用
Intersect返回在两个单独的集合中发现相同的值的集合不适用不适用
Union将两个不同集合的内容合并到一个列表中,也没有任何重复的内容不适用不适用

Distinct示例

VB

无涯教程网

Module Module1

   Sub Main()
  
      Dim classGrades = New System.Collections.Generic.List(Of Integer) From {63, 68, 71, 75, 68, 92, 75}

      Dim distinctQuery = From grade In classGrades 
                          Select grade Distinct

      Dim sb As New System.Text.StringBuilder("The distinct grades are: ")
	  
      For Each number As Integer In distinctQuery
         sb.Append(number & " ")
      Next

      MsgBox(sb.ToString())
	  
   End Sub
   
End Module

编译并执行上述代码后,将产生以下输出-

The distinct grades are: 63 68 71 75 92

Except的示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
         double[] numbers2 = { 2.2 };

         IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);

         foreach (double number in onlyInFirstSet)
            Console.WriteLine(number);
            Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim numbers1() As Double = {2.0, 2.1, 2.2, 2.3, 2.4, 2.5}
      Dim numbers2() As Double = {2.2}

      Dim onlyInFirstSet As IEnumerable(Of Double) = numbers1.Except(numbers2)

      Dim output As New System.Text.StringBuilder
	  
      For Each number As Double In onlyInFirstSet
         output.AppendLine(number)
         Console.WriteLine(number)
      Next
	  
      Console.ReadLine()
     
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

2
2.1
2.3
2.4
2.5

Intersect示例

C#

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

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

         int[] id1 = { 44, 26, 92, 30, 71, 38 };
         int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

         IEnumerable<int> both = id1.Intersect(id2);

         foreach (int id in both)
            Console.WriteLine(id);
            Console.ReadLine();
      }
   }
}	

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim id1() As Integer = {44, 26, 92, 30, 71, 38}
      Dim id2() As Integer = {39, 59, 83, 47, 26, 4, 30}

      Dim intersection As IEnumerable(Of Integer) = id1.Intersect(id2)

      Dim output As New System.Text.StringBuilder
	  
      For Each id As Integer In intersection
         output.AppendLine(id)
         Console.WriteLine(id)
      Next
     
      Console.ReadLine()
     
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

26
30

Union示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
         int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };

         IEnumerable<int> union = ints1.Union(ints2);

         foreach (int num in union) {
            Console.Write("{0} ", num);
            Console.Write("\n");
         }
			
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim ints1() As Integer = {5, 3, 9, 7, 5, 9, 3, 7}
      Dim ints2() As Integer = {8, 3, 6, 4, 4, 9, 1, 0}

      Dim union As IEnumerable(Of Integer) = ints1.Union(ints2)

      Dim output As New System.Text.StringBuilder
	  
      For Each num As Integer In union
         output.AppendLine(num & " ")
         Console.WriteLine(num & " ")
      Next
     
      Console.ReadLine()
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

5
3 
9 
7 
8 
6 
4 
1 
0

Equality

比较两个句子(可枚举)并确定它们是否完全匹配。

Operator说明 C#查询表达式语法 VB查询表达式语法
SequenceEqual如果发现两个序列彼此相同,则返回布尔值不适用不适用

SequenceEqual示例

C#

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

namespace Operators {
   class SequenceEqual {
      static void Main(string[] args) {
      
         Pet barley=new Pet() { Name="Barley", Age=4 };
         Pet boots=new Pet() { Name="Boots", Age=1 };
         Pet whiskers=new Pet() { Name="Whiskers", Age=6 };

         List<Pet> pets1=new List<Pet>() { barley, boots };
         List<Pet> pets2=new List<Pet>() { barley, boots };
         List<Pet> pets3=new List<Pet>() { barley, boots, whiskers };

         bool equal=pets1.SequenceEqual(pets2);
         bool equal3=pets1.SequenceEqual(pets3);

         Console.WriteLine("The lists pets1 and pets2 {0} equal.", equal ? "are" :"are not");
         Console.WriteLine("The lists pets1 and pets3 {0} equal.", equal3 ? "are" :"are not");

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }

      class Pet {
         public string Name { get; set; }
         public int Age { get; set; }
      }
   }
}

VB

无涯教程网

Module Module1
   Sub Main()

      Dim barley As New Pet With {.Name="Barley", .Age=4}
      Dim boots As New Pet With {.Name="Boots", .Age=1}
      Dim whiskers As New Pet With {.Name="Whiskers", .Age=6}

      Dim pets1 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots})
      Dim pets2 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots})
      Dim pets3 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots, whiskers})

      Dim equal As Boolean=pets1.SequenceEqual(pets2)
      Dim equal3 As Boolean=pets1.SequenceEqual(pets3)

      Console.WriteLine("The lists pets1 and pets2 {0} equal.", IIf(equal, "are", "are not"))
      Console.WriteLine("The lists pets1 and pets3 {0} equal.", IIf(equal3, "are", "are not"))

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
  
   End Sub

   Class Pet
      Public Property Name As String
      Public Property Age As Integer
   End Class
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

The lists pets1 and pets2 are equal.
The lists pets1 and pets3 are not equal.

Press any key to continue.

Element Operators

除DefaultIfEmpty外,其余所有八个标准查询元素运算符都将返回集合中的单个元素。

Operator说明 C#查询表达式语法 VB查询表达式语法
ElementAt返回存在于集合中特定索引中的元素不适用不适用
ElementAtOrDefault与ElementAt相同,除了在特定索引超出范围的情况下还会返回默认值不适用不适用
First检索集合中的第一个元素或满足特定条件的第一个元素不适用不适用
FirstOrDefault与First相同,除了在不存在此类元素的情况下还会返回默认值不适用不适用
Last检索集合中存在的最后一个元素或满足特定条件的最后一个元素不适用不适用
LastOrDefault与Last相同,除了在不存在任何此类元素的情况下也会返回默认值不适用不适用
Single返回集合的lone元素或满足特定条件的lone元素不适用不适用
SingleOrDefault与Single相同,不同之处在于,如果不存在任何此类孤元素,它还会返回默认值不适用不适用
DefaultIfEmpty如果集合或列表为空或为空,则返回默认值不适用不适用

ElementAt的示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", 
                       "Hedlund, Magnus", "Ito, Shu" };
         Random random = new Random(DateTime.Now.Millisecond);

         string name = names.ElementAt(random.Next(0, names.Length));

         Console.WriteLine("The name chosen at random is '{0}'.", name);
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim names() As String = _{"Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", 
	                     "Hedlund, Magnus", "Ito, Shu"}

      Dim random As Random = New Random(DateTime.Now.Millisecond)

      Dim name As String = names.ElementAt(random.Next(0, names.Length))

      MsgBox("The name chosen at random is " & name)
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

The name chosen at random is Ito, Shu

注意-在这里,以上输出将动态更改,并且名称将被随机选择。

First方法示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };

         int first = numbers.First();

         Console.WriteLine(first);
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()
   
      Dim numbers() As Integer = _{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
      
      Dim first As Integer = numbers.First()

      MsgBox(first)
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

9

Enumerable.Last方法示例

C#

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

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };

         int last = numbers.Last();

         Console.WriteLine(last);
         Console.ReadLine();
      }
   }
}

VB

无涯教程网

Module Module1

   Sub Main()

      Dim numbers() As Integer = _{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19};
      
      Dim last As Integer = numbers.Last()

      MsgBox(last)
	  
   End Sub
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

19

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

iOS开发高手课 -〔戴铭〕

Flutter核心技术与实战 -〔陈航〕

软件设计之美 -〔郑晔〕

跟着高手学复盘 -〔张鹏〕

爆款文案修炼手册 -〔乐剑峰〕

Go 语言项目开发实战 -〔孔令飞〕

业务开发算法50讲 -〔黄清昊〕

说透低代码 -〔陈旭〕

好记忆不如烂笔头。留下您的足迹吧 :)