本文概述
在LINQ中, 只要指定条件包含表达式, 就可以使用TakeWhile运算符从数据源的列表/集合中获取元素。
LINQ TakeWhile运算符的语法
使用LINQ TakeWhile运算符的语法是根据指定条件从列表中获取元素。
C#代码
IEnumerable<string> result = countries.TakeWhile(x => x.StartsWith("U"));
从上面的语法中, 我们从元素以” U”开头的列表中获取元素。
方法语法中的LINQ TakeWhile示例
这是在方法语法中使用LINQ TakeWhile来从列表/集合中获取元素的示例。
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<string> 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();
}
}
}
在上面的示例中, 我们使用了TakeWhile()运算符和一个lambda表达式, 在其中指定了条件, 该条件将选择以” U”开头的国家。因此, 它仅返回前两个元素。
输出

查询语法中的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<string> result = (from x in countries select x).TakeWhile(x => x.StartsWith("U"));
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
输出
执行完上面的程序后, 我们得到如下所示的输出:
