LINQ 中的过滤运算符
过滤是一种限制结果集的操作,使其仅包含满足特定条件的选定元素。
| 运算符 | 描述 | C# 查询表达式语法 | VB 查询表达式语法 |
|---|---|---|---|
| Where | 根据谓词函数过滤值 | where | Where |
| OfType | 根据值作为指定类型 | 不适用 | 不适用 |
Where 示例 - 查询表达式
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 编译并执行上述代码时,会产生以下结果 −
set

linq_query_operators.html