在LINQ中,只要指定的条件包含表达式,就使用TakeWhile运算符从数据源的列表/集合中获取元素。
使用LINQ TakeWhile运算符的语法是根据指定的条件从列表中获取元素。
链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-takewhile-partition-operator.html
来源:LearnFk无涯教程网
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 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.*/ IEnumerableresult = 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运算符从列表中获取元素的示例。
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"). IEnumerableresult = (from x in countries select x).TakeWhile(x => x.StartsWith("U")); foreach (string s in result) { Console.WriteLine(s); } Console.ReadLine(); } } }
输出:
执行上述程序后,我们会得到如下所示的输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)