CSharp - Use Take operator to make query faster

Introduction

The following code is more efficient by using the Take operator instead of relying on the index being passed into the lambda expression.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*  w  w w  .  ja v  a  2 s  .  c  o  m*/
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<char> chars = codeNames.Take(5).SelectMany(s => s.ToArray());
        
        foreach (char ch in chars)
            Console.WriteLine(ch);

    }
}

Result

The code above takes only the first five elements from the input sequence.

Then only the first five are passed as the input sequence into SelectMany.

Related Topic