CSharp - LINQ Take

Introduction

The Take operator returns a number of elements from the input sequence starting from the beginning of the sequence.

Prototypes

public static IEnumerable<T> Take<T>(
  this IEnumerable<T> source,
  int count);

This prototype of Take will receive an input source sequence and an integer named count.

The count parameter specifies how many input elements to return.

Take operator will return an object that, when enumerated, will yield the first count number of elements from the input sequence.

If the count value is greater than the number of elements in the input sequence, then every element of the input sequence will be yielded into the output sequence.

Exceptions

ArgumentNullException is thrown if the input source sequence is null.

This code will return the first five input elements from the codeNames array.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  ww w . j  av  a  2s. c o m
{
    static void Main(string[] args)
    {
      string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};

      IEnumerable<string> items = codeNames.Take(5);

      foreach (string item in items)
          Console.WriteLine(item);


    }
}

Result

Related Topics