Linq TakeWhile运算符

Linq TakeWhile运算符 首页 / LinQ入门教程 / Linq TakeWhile运算符

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

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示例

下面是使用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




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Elasticsearch核心技术与实战 -〔阮一鸣〕

Swift核心技术与实战 -〔张杰〕

MongoDB高手课 -〔唐建法(TJ)〕

跟月影学可视化 -〔月影〕

体验设计案例课 -〔炒炒〕

基于人因的用户体验设计课 -〔刘石〕

陈天 · Rust 编程第一课 -〔陈天〕

Kubernetes入门实战课 -〔罗剑锋〕

云原生架构与GitOps实战 -〔王炜〕

好记忆不如烂笔头。留下您的足迹吧 :)