1.where
Filtering Operators | Description |
---|---|
Where | Returns values from the collection based on a predicate function |
OfType | Returns values from the collection based on a specified type. However, it will depend on their ability to cast to a specified type. |
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);
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;
方式2
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;
方式3
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的第二个扩展方法包含集合的index索引
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 element return true; return false; }); foreach (var std in filteredResult) Console.WriteLine(std.StudentName);
多个where从句
var filteredResult = from s in studentList where s.Age > 12 where s.Age < 20 select s;
var filteredResult = studentList.Where(s => s.Age > 12).Where(s => s.Age < 20);
需要记住的几点:
1.Where根据特定条件来筛选集合元素
2.where扩展方法有2个重载,使用第二个重载方法可以知道当前元素在集合中的索引位置
3.方法语法需要整个lambda表达式,而查询语法仅仅需要表达式主体
4.在单一的LINQ查询中可以使用多个where从句