跳转至

筛选运算⚓︎

一、筛选运算方法⚓︎

在查询语法中,通过 where 关键字完成按条件筛选结果,比如:

var queryLondonCustomers = from cust in customers
                           where cust.City == "London"
                           select cust;

在方法语法中,存在标准查询运算符方法来完成这一功能,下面列出列这些方法,需要注意的是不是所有方法都有对应的查询语法关键字:

方法 说明 查询语法 链接
OfType 根据指定类型筛选的元素 × Enumerable.OfTypeQueryable.OfType
Where 根据指定条件筛选元素 where Enumerable.WhereQueryable.Where

二、OfType⚓︎

OfType() 方法用来根据指定类型筛选元素,得到的结果集是只包含指定类型的结果。

System.Collections.ArrayList fruits = new System.Collections.ArrayList(5); fruits.Add("Mango"); 
fruits.Add("Orange"); 
fruits.Add("Apple"); 
fruits.Add(3.0); 
fruits.Add("Banana");

IEnumerable<string> query1 = fruits.OfType<string>();

Console.WriteLine("Elements of type 'string' are:"); 
foreach (string fruit in query1) 
{
    Console.WriteLine(fruit); 
}

/* Output:
    Elements of type 'string' are:
    Mango
    Orange
    Apple
    Banana
*/

三、Where⚓︎

Where() 方法用来按指定条件筛选元素,与查询语法中的 where 关键字功能相同。下例展示了查询语法与方法语法的使用:

List<string> fruits = new List<string> { 
    "apple", 
    "passionfruit", 
    "banana", 
    "mango",
    "orange", 
    "blueberry", 
    "grape", 
    "strawberry" 
};

// 查询语法
IEnumerable<string> query1 = from fruit in fruits
                        where fruit.Length < 6 
                        select fruit;

foreach (string fruit in query1)
    Console.WriteLine(fruit);

Console.WriteLine();

// 方法语法
IEnumerable<string> query2 = fruits.Where(fruit => fruit.Length < 6);

foreach (string fruit in query2)
    Console.WriteLine(fruit);

/*
This code produces the following output:
    apple
    mango
    grape

    apple
    mango
    grape
*/