无涯教程-Linq TakeWhile运算符

53 阅读1分钟

在LINQ中,只要指定的条件包含表达式,就使用TakeWhile运算符从数据源的列表/集合中获取元素。

LINQ TakeWhile运算符的语法

使用LINQ TakeWhile运算符的语法是根据指定的条件从列表中获取元素。

C#代码

IEnumerable<string> result = countries.TakeWhile(x => x.StartsWith("U"));

From the above syntax, we are getting the elements from the list where the elements starts with "U".

方法语法中的LINQ TakeWhile示例

下面是使用LINQ TakeWhile in方法语法从列表/集合获取元素的示例。

C#代码

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

namespace ConsoleApp1 { class Program { static void Main(string[] args) { //Array countries is created of string type. string[] countries = { "US", "UK", "Russia", "China", "Australia", "Argentina" }; /TakeWhile operator is used which will print the values until the specified condition is satisfied./ IEnumerable result = countries.TakeWhile(x => x.StartsWith("U")); //foreach loop will print the value of the result foreach (string s in result) { Console.WriteLine(s); } Console.ReadLine(); } } }

In the above example, we used TakeWhile () operator and a lambda expression in which we specified the condition which will select the countries that starts with "U." So, it returns only the first two elements.

输出:

LINQ TakeWhile Partition Operator

查询语法中的LINQ TakeWhile示例

下面是在查询语法中使用LINQ TakeWhile运算符从列表中获取元素的示例。

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

namespace ConsoleApp1 { class Program { static void Main(string[] args) { string[] countries = { "US", "UK", "China", "Russia", "Argentina", "India" }; //apply the query syntax to print the values upto the specified condition.StartWith("U"). IEnumerable result = (from x in countries select x).TakeWhile(x => x.StartsWith("U")); foreach (string s in result) { Console.WriteLine(s); } Console.ReadLine(); } } }

输出:

执行上述程序后,我们会得到如下所示的输出:

LINQ TakeWhile Partition Operator




参考链接

www.learnfk.com/linq/linq-t…