个性化阅读
专注于IT技术分析

LINQ take分区运算符

本文概述

在LINQ中, “Take算符”用于从列表/集合中按顺序获取指定数量的元素。 LINQ要求操作员从集合或列表的开始处返回指定数量的元素。

我们将一个参数传递给LINQ Take()运算符, 该运算符将指定要返回的元素数。

LINQ Take运算符的语法

LINQ Take运算符的语法是从列表/集合中返回指定数量的元素。

C#代码

IEnumerable<string> result = countries.Take(3);

方法语法中的LINQ Take运算符示例

方法语法中的LINQ Takes()运算符示例从列表或集合中返回指定数量的元素。

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)
        {
//create an array countries of string type with the initialized array
            string[] countries = { "India", "USA", "Russia", "China", "Australia", "Argentina" };
//here take() method will return the value from the String array upto three numbers.
            IEnumerable<string> result = countries.Take(3);
            foreach (string s in result)
            {
                Console.WriteLine(s);
            }
                Console.ReadLine();
        }
    }
}

上面的程序显示我们有一个包含国家的字符串数组。在这里, 我们要显示数组中仅有的前三个国家。这就是为什么我们使用Take运算符并传递count运算符, 以便它返回数组中元素数的原因。

输出

LINQ take分区运算符

查询语法中的LINQ Take()运算符示例

如果我们在查询语法中使用LINQ Take()运算符, 示例将如下所示:

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)
        {


            string[] countries = { "India", "USA", "Russia", "China", "Australia", "Argentina" };

            IEnumerable<string> result = (from x in countries select x).Take(3);

            foreach (string s in result)

            {

                Console.WriteLine(s);

            }

            Console.ReadLine();

        }

    }
    }

输出

LINQ take分区运算符

赞(0)
未经允许不得转载:srcmini » LINQ take分区运算符

评论 抢沙发

评论前必须登录!