English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ 过滤运算符 Where

LINQ中的过滤运算符根据某些给定的标准过滤序列(集合)。

下表列出了LINQ中所有可用的过滤运算符。

筛选运算符描述
Where

根据谓词函数从集合中返回值。

OfType

根据指定类型返回集合中的值。 然而,它取决于它们是否能够向指定类型转换。

Where

Where运算符(Linq扩展方法)基于给定的条件表达式过滤集合并返回新集合。可以将标准指定为lambda表达式或Func委托类型。

Where扩展方法有以下两个重载。两种重载方法都接受Func委托类型参数。一个重载需要Func <TSource,bool>输入参数,第二个重载方法需要Func <TSource,int,bool>输入参数,其中int用于索引:

Where方法重载:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, 
                                                  Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, 
                                                  Func<TSource, int, bool> predicate);

查询语法中的Where子句

下面的查询示例使用Where运算符从给定的集合(序列)中筛选出青少年的学生。它使用lambda表达式作为谓词函数。

IList<Student> studentList = new List<Student>() { 
        new Student() { StudentID = 1, StudentName = "John", Age = 13}
        new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 }
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 }
        new Student() { StudentID = 4, StudentName = "Ram", Age = 20},
        new Student() { StudentID = 5, StudentName = "Ron", Age = 15 } 
    };
var filteredResult = from s in studentList
                    where s.Age > 12 && s.Age < 20
                    select s.StudentName;
Dim studentList = New List(Of Student) From {
        New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
        New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
        New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
        New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
        New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
    }
Dim filteredResult = From s In studentList
                     Where s.Age > 12 And s.Age < 20
                     Select s.StudentName

在上面的示例中,filteredResult 将在查询执行后包括以下学生。

John
Bill
Ron

在上面的示例查询中,lambda表达式主体 s.Age > 12 && s.Age < 20 作为评估集合中每个学生的谓词函数传递。Func<TSource, bool>

另外,您还可以将Func类型委托与匿名方法一起使用,作为如下的谓词函数进行传递(输出是相同的):

Func<Student,bool> isTeenAger = delegate(Student s) { 
                                    return s.Age > 12 && s.Age < 20; 
                                };
var filteredResult = from s in studentList
                     where isTeenAger(s)
                     select s;

你也可以通过Where()方法的重载调用任何与Func形参匹配的方法。

public static void Main()
{
    var filteredResult = from s in studentList
                         where isTeenAger(s)
                         select s;
}
public static bool IsTeenAger(Student stud)
{
    return stud.Age > 12 && stud.Age < 20;  
}

方法语法中的where扩展方法

与查询语法不同,您需要将整个lambda表达式作为谓词函数传递,而不仅仅是LINQ方法语法中的表达式主体。

var filteredResult = studentList.Where(s => s.Age > 12 && s.Age < 20);
Dim filteredResult = studentList.Where(Function(s) s.Age > 12 And s.Age < 20 )

如上所述,Where扩展方法还具有第二重载,其包括集合中当前元素的索引。如果需要,可以在逻辑中使用该索引。

以下示例使用Where子句过滤出集合中的奇数元素,仅返回偶数元素。请记住,索引从零开始。

IList<Student> studentList = new List<Student>() { 
        new Student() { StudentID = 1, StudentName = "John", Age = 18 }
        new Student() { StudentID = 2, StudentName = "Steve",  Age = 15 }
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 }
        new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
        new Student() { StudentID = 5, StudentName = "Ron", Age = 19 } 
    };
var filteredResult = studentList.Where((s, i) => { 
            if(i % 2 == 0) // If it is even
                return true;
                
        return false;
    });
foreach (var std in filteredResult)
        Console.WriteLine(std.StudentName);

 

Output:
John
Bill
Ron

Multiple where clauses

You can call the Where() extension method multiple times in a single LINQ query.

Example: Multiple where clauses in query syntax in C#
var filteredResult = from s in studentList
                        where s.Age > 12                    
                        where s.Age < 20                    
                        select s;
Example: Multiple where clauses in method syntax in C#
var filteredResult = studentList.Where(s => s.Age > 12).Where(s => s.Age < 20);

  Key Points to Remember

  1. Where Used to filter the collection based on a given standard.

  2. Among which there are two overloaded methods for the extension method. Using the second overloaded method can know the current index of the element in the collection.

  3. Method syntax requires the entire lambda expression in the Where extension method, while query syntax only needs the expression body.

  4. In a single LINQ query, multipleWhereExtension methods are effective.